LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 472031e0b71f3195f7f21b1f2b20de09fd07bb56.info Lines: 78.5 % 9631 7562
Test Date: 2025-05-26 10:37:33 Functions: 62.1 % 472 293

            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, LsnLease, TimelineArchivalState, TimelineState, TopTenantShardItem,
      38              :     WalRedoManagerStatus,
      39              : };
      40              : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
      41              : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
      42              : use remote_timeline_client::index::GcCompactionState;
      43              : use remote_timeline_client::manifest::{
      44              :     LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
      45              : };
      46              : use remote_timeline_client::{
      47              :     FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
      48              :     download_tenant_manifest,
      49              : };
      50              : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
      51              : use storage_broker::BrokerClientChannel;
      52              : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
      53              : use timeline::import_pgdata::ImportingTimeline;
      54              : use timeline::offload::{OffloadError, offload_timeline};
      55              : use timeline::{
      56              :     CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
      57              : };
      58              : use tokio::io::BufReader;
      59              : use tokio::sync::{Notify, Semaphore, watch};
      60              : use tokio::task::JoinSet;
      61              : use tokio_util::sync::CancellationToken;
      62              : use tracing::*;
      63              : use upload_queue::NotInitialized;
      64              : use utils::circuit_breaker::CircuitBreaker;
      65              : use utils::crashsafe::path_with_suffix_extension;
      66              : use utils::sync::gate::{Gate, GateGuard};
      67              : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
      68              : use utils::try_rcu::ArcSwapExt;
      69              : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
      70              : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
      71              : 
      72              : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf};
      73              : use self::metadata::TimelineMetadata;
      74              : use self::mgr::{GetActiveTenantError, GetTenantError};
      75              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      76              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      77              : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
      78              : use self::timeline::{
      79              :     EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
      80              : };
      81              : use crate::basebackup_cache::BasebackupPrepareSender;
      82              : use crate::config::PageServerConf;
      83              : use crate::context;
      84              : use crate::context::RequestContextBuilder;
      85              : use crate::context::{DownloadBehavior, RequestContext};
      86              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
      87              : use crate::l0_flush::L0FlushGlobalState;
      88              : use crate::metrics::{
      89              :     BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
      90              :     INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_OFFLOADED_TIMELINES,
      91              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC, remove_tenant_metrics,
      92              : };
      93              : use crate::task_mgr::TaskKind;
      94              : use crate::tenant::config::LocationMode;
      95              : use crate::tenant::gc_result::GcResult;
      96              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
      97              : use crate::tenant::remote_timeline_client::{
      98              :     INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
      99              : };
     100              : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
     101              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     102              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     103              : use crate::virtual_file::VirtualFile;
     104              : use crate::walingest::WalLagCooldown;
     105              : use crate::walredo::{PostgresRedoManager, RedoAttemptType};
     106              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
     107              : 
     108            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     109              : use utils::crashsafe;
     110              : use utils::generation::Generation;
     111              : use utils::id::TimelineId;
     112              : use utils::lsn::{Lsn, RecordLsn};
     113              : 
     114              : pub mod blob_io;
     115              : pub mod block_io;
     116              : pub mod vectored_blob_io;
     117              : 
     118              : pub mod disk_btree;
     119              : pub(crate) mod ephemeral_file;
     120              : pub mod layer_map;
     121              : 
     122              : pub mod metadata;
     123              : pub mod remote_timeline_client;
     124              : pub mod storage_layer;
     125              : 
     126              : pub mod checks;
     127              : pub mod config;
     128              : pub mod mgr;
     129              : pub mod secondary;
     130              : pub mod tasks;
     131              : pub mod upload_queue;
     132              : 
     133              : pub(crate) mod timeline;
     134              : 
     135              : pub mod size;
     136              : 
     137              : mod gc_block;
     138              : mod gc_result;
     139              : pub(crate) mod throttle;
     140              : 
     141              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     142              : 
     143              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     144              : // re-export for use in walreceiver
     145              : pub use crate::tenant::timeline::WalReceiverInfo;
     146              : 
     147              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     148              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     149              : 
     150              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     151              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     152              : 
     153              : /// References to shared objects that are passed into each tenant, such
     154              : /// as the shared remote storage client and process initialization state.
     155              : #[derive(Clone)]
     156              : pub struct TenantSharedResources {
     157              :     pub broker_client: storage_broker::BrokerClientChannel,
     158              :     pub remote_storage: GenericRemoteStorage,
     159              :     pub deletion_queue_client: DeletionQueueClient,
     160              :     pub l0_flush_global_state: L0FlushGlobalState,
     161              :     pub basebackup_prepare_sender: BasebackupPrepareSender,
     162              : }
     163              : 
     164              : /// A [`TenantShard`] is really an _attached_ tenant.  The configuration
     165              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     166              : /// in this struct.
     167              : #[derive(Clone)]
     168              : pub(super) struct AttachedTenantConf {
     169              :     tenant_conf: pageserver_api::models::TenantConfig,
     170              :     location: AttachedLocationConfig,
     171              :     /// The deadline before which we are blocked from GC so that
     172              :     /// leases have a chance to be renewed.
     173              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     174              : }
     175              : 
     176              : impl AttachedTenantConf {
     177          117 :     fn new(
     178          117 :         tenant_conf: pageserver_api::models::TenantConfig,
     179          117 :         location: AttachedLocationConfig,
     180          117 :     ) -> Self {
     181              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     182              :         //
     183              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     184              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     185              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     186          117 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     187          117 :             Some(
     188          117 :                 tokio::time::Instant::now()
     189          117 :                     + tenant_conf
     190          117 :                         .lsn_lease_length
     191          117 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     192          117 :             )
     193              :         } else {
     194              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     195              :             // because we don't do GC in these modes.
     196            0 :             None
     197              :         };
     198              : 
     199          117 :         Self {
     200          117 :             tenant_conf,
     201          117 :             location,
     202          117 :             lsn_lease_deadline,
     203          117 :         }
     204          117 :     }
     205              : 
     206          117 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     207          117 :         match &location_conf.mode {
     208          117 :             LocationMode::Attached(attach_conf) => {
     209          117 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     210              :             }
     211              :             LocationMode::Secondary(_) => {
     212            0 :                 anyhow::bail!(
     213            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     214            0 :                 )
     215              :             }
     216              :         }
     217          117 :     }
     218              : 
     219          381 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     220          381 :         self.lsn_lease_deadline
     221          381 :             .map(|d| tokio::time::Instant::now() < d)
     222          381 :             .unwrap_or(false)
     223          381 :     }
     224              : }
     225              : struct TimelinePreload {
     226              :     timeline_id: TimelineId,
     227              :     client: RemoteTimelineClient,
     228              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     229              :     previous_heatmap: Option<PreviousHeatmap>,
     230              : }
     231              : 
     232              : pub(crate) struct TenantPreload {
     233              :     /// The tenant manifest from remote storage, or None if no manifest was found.
     234              :     tenant_manifest: Option<TenantManifest>,
     235              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     236              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     237              : }
     238              : 
     239              : /// When we spawn a tenant, there is a special mode for tenant creation that
     240              : /// avoids trying to read anything from remote storage.
     241              : pub(crate) enum SpawnMode {
     242              :     /// Activate as soon as possible
     243              :     Eager,
     244              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     245              :     Lazy,
     246              : }
     247              : 
     248              : ///
     249              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     250              : ///
     251              : pub struct TenantShard {
     252              :     // Global pageserver config parameters
     253              :     pub conf: &'static PageServerConf,
     254              : 
     255              :     /// The value creation timestamp, used to measure activation delay, see:
     256              :     /// <https://github.com/neondatabase/neon/issues/4025>
     257              :     constructed_at: Instant,
     258              : 
     259              :     state: watch::Sender<TenantState>,
     260              : 
     261              :     // Overridden tenant-specific config parameters.
     262              :     // We keep pageserver_api::models::TenantConfig sturct here to preserve the information
     263              :     // about parameters that are not set.
     264              :     // This is necessary to allow global config updates.
     265              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     266              : 
     267              :     tenant_shard_id: TenantShardId,
     268              : 
     269              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     270              :     shard_identity: ShardIdentity,
     271              : 
     272              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     273              :     /// Does not change over the lifetime of the [`TenantShard`] object.
     274              :     ///
     275              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     276              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     277              :     generation: Generation,
     278              : 
     279              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     280              : 
     281              :     /// During timeline creation, we first insert the TimelineId to the
     282              :     /// creating map, then `timelines`, then remove it from the creating map.
     283              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     284              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     285              : 
     286              :     /// Possibly offloaded and archived timelines
     287              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     288              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     289              : 
     290              :     /// Tracks the timelines that are currently importing into this tenant shard.
     291              :     ///
     292              :     /// Note that importing timelines are also present in [`Self::timelines_creating`].
     293              :     /// Keep this in mind when ordering lock acquisition.
     294              :     ///
     295              :     /// Lifetime:
     296              :     /// * An imported timeline is created while scanning the bucket on tenant attach
     297              :     ///   if the index part contains an `import_pgdata` entry and said field marks the import
     298              :     ///   as in progress.
     299              :     /// * Imported timelines are removed when the storage controller calls the post timeline
     300              :     ///   import activation endpoint.
     301              :     timelines_importing: std::sync::Mutex<HashMap<TimelineId, ImportingTimeline>>,
     302              : 
     303              :     /// The last tenant manifest known to be in remote storage. None if the manifest has not yet
     304              :     /// been either downloaded or uploaded. Always Some after tenant attach.
     305              :     ///
     306              :     /// Initially populated during tenant attach, updated via `maybe_upload_tenant_manifest`.
     307              :     ///
     308              :     /// Do not modify this directly. It is used to check whether a new manifest needs to be
     309              :     /// uploaded. The manifest is constructed in `build_tenant_manifest`, and uploaded via
     310              :     /// `maybe_upload_tenant_manifest`.
     311              :     remote_tenant_manifest: tokio::sync::Mutex<Option<TenantManifest>>,
     312              : 
     313              :     // This mutex prevents creation of new timelines during GC.
     314              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     315              :     // `timelines` mutex during all GC iteration
     316              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     317              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     318              :     // timeout...
     319              :     gc_cs: tokio::sync::Mutex<()>,
     320              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     321              : 
     322              :     /// Provides access to timeline data sitting in the remote storage.
     323              :     pub(crate) remote_storage: GenericRemoteStorage,
     324              : 
     325              :     /// Access to global deletion queue for when this tenant wants to schedule a deletion.
     326              :     deletion_queue_client: DeletionQueueClient,
     327              : 
     328              :     /// A channel to send async requests to prepare a basebackup for the basebackup cache.
     329              :     basebackup_prepare_sender: BasebackupPrepareSender,
     330              : 
     331              :     /// Cached logical sizes updated updated on each [`TenantShard::gather_size_inputs`].
     332              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     333              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     334              : 
     335              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     336              : 
     337              :     /// Track repeated failures to compact, so that we can back off.
     338              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     339              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     340              : 
     341              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     342              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     343              : 
     344              :     /// Scheduled gc-compaction tasks.
     345              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     346              : 
     347              :     /// If the tenant is in Activating state, notify this to encourage it
     348              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     349              :     /// background warmup.
     350              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     351              : 
     352              :     /// Time it took for the tenant to activate. Zero if not active yet.
     353              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     354              : 
     355              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     356              :     // Timelines' cancellation token.
     357              :     pub(crate) cancel: CancellationToken,
     358              : 
     359              :     // Users of the TenantShard such as the page service must take this Gate to avoid
     360              :     // trying to use a TenantShard which is shutting down.
     361              :     pub(crate) gate: Gate,
     362              : 
     363              :     /// Throttle applied at the top of [`Timeline::get`].
     364              :     /// All [`TenantShard::timelines`] of a given [`TenantShard`] instance share the same [`throttle::Throttle`] instance.
     365              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     366              : 
     367              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     368              : 
     369              :     /// An ongoing timeline detach concurrency limiter.
     370              :     ///
     371              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     372              :     /// to have two running at the same time. A different one can be started if an earlier one
     373              :     /// has failed for whatever reason.
     374              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     375              : 
     376              :     /// `index_part.json` based gc blocking reason tracking.
     377              :     ///
     378              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     379              :     /// proceeding.
     380              :     pub(crate) gc_block: gc_block::GcBlock,
     381              : 
     382              :     l0_flush_global_state: L0FlushGlobalState,
     383              : }
     384              : impl std::fmt::Debug for TenantShard {
     385            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     386            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     387            0 :     }
     388              : }
     389              : 
     390              : pub(crate) enum WalRedoManager {
     391              :     Prod(WalredoManagerId, PostgresRedoManager),
     392              :     #[cfg(test)]
     393              :     Test(harness::TestRedoManager),
     394              : }
     395              : 
     396              : #[derive(thiserror::Error, Debug)]
     397              : #[error("pageserver is shutting down")]
     398              : pub(crate) struct GlobalShutDown;
     399              : 
     400              : impl WalRedoManager {
     401            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     402            0 :         let id = WalredoManagerId::next();
     403            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     404            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     405            0 :         match &mut *guard {
     406            0 :             Some(map) => {
     407            0 :                 map.insert(id, Arc::downgrade(&arc));
     408            0 :                 Ok(arc)
     409              :             }
     410            0 :             None => Err(GlobalShutDown),
     411              :         }
     412            0 :     }
     413              : }
     414              : 
     415              : impl Drop for WalRedoManager {
     416            5 :     fn drop(&mut self) {
     417            5 :         match self {
     418            0 :             Self::Prod(id, _) => {
     419            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     420            0 :                 if let Some(map) = &mut *guard {
     421            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     422            0 :                 }
     423              :             }
     424              :             #[cfg(test)]
     425            5 :             Self::Test(_) => {
     426            5 :                 // Not applicable to test redo manager
     427            5 :             }
     428              :         }
     429            5 :     }
     430              : }
     431              : 
     432              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     433              : /// the walredo processes outside of the regular order.
     434              : ///
     435              : /// This is necessary to work around a systemd bug where it freezes if there are
     436              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     437              : #[allow(clippy::type_complexity)]
     438              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     439              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     440            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     441              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     442              : pub(crate) struct WalredoManagerId(u64);
     443              : impl WalredoManagerId {
     444            0 :     pub fn next() -> Self {
     445              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     446            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     447            0 :         if id == 0 {
     448            0 :             panic!(
     449            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     450            0 :             );
     451            0 :         }
     452            0 :         Self(id)
     453            0 :     }
     454              : }
     455              : 
     456              : #[cfg(test)]
     457              : impl From<harness::TestRedoManager> for WalRedoManager {
     458          117 :     fn from(mgr: harness::TestRedoManager) -> Self {
     459          117 :         Self::Test(mgr)
     460          117 :     }
     461              : }
     462              : 
     463              : impl WalRedoManager {
     464            3 :     pub(crate) async fn shutdown(&self) -> bool {
     465            3 :         match self {
     466            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     467              :             #[cfg(test)]
     468              :             Self::Test(_) => {
     469              :                 // Not applicable to test redo manager
     470            3 :                 true
     471              :             }
     472              :         }
     473            3 :     }
     474              : 
     475            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     476            0 :         match self {
     477            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     478            0 :             #[cfg(test)]
     479            0 :             Self::Test(_) => {
     480            0 :                 // Not applicable to test redo manager
     481            0 :             }
     482            0 :         }
     483            0 :     }
     484              : 
     485              :     /// # Cancel-Safety
     486              :     ///
     487              :     /// This method is cancellation-safe.
     488        26774 :     pub async fn request_redo(
     489        26774 :         &self,
     490        26774 :         key: pageserver_api::key::Key,
     491        26774 :         lsn: Lsn,
     492        26774 :         base_img: Option<(Lsn, bytes::Bytes)>,
     493        26774 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     494        26774 :         pg_version: u32,
     495        26774 :         redo_attempt_type: RedoAttemptType,
     496        26774 :     ) -> Result<bytes::Bytes, walredo::Error> {
     497        26774 :         match self {
     498            0 :             Self::Prod(_, mgr) => {
     499            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     500            0 :                     .await
     501              :             }
     502              :             #[cfg(test)]
     503        26774 :             Self::Test(mgr) => {
     504        26774 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     505        26774 :                     .await
     506              :             }
     507              :         }
     508        26774 :     }
     509              : 
     510            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     511            0 :         match self {
     512            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     513            0 :             #[cfg(test)]
     514            0 :             WalRedoManager::Test(_) => None,
     515            0 :         }
     516            0 :     }
     517              : }
     518              : 
     519              : /// A very lightweight memory representation of an offloaded timeline.
     520              : ///
     521              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     522              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     523              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     524              : /// more offloaded timelines than we can manage ones that aren't.
     525              : pub struct OffloadedTimeline {
     526              :     pub tenant_shard_id: TenantShardId,
     527              :     pub timeline_id: TimelineId,
     528              :     pub ancestor_timeline_id: Option<TimelineId>,
     529              :     /// Whether to retain the branch lsn at the ancestor or not
     530              :     pub ancestor_retain_lsn: Option<Lsn>,
     531              : 
     532              :     /// When the timeline was archived.
     533              :     ///
     534              :     /// Present for future flattening deliberations.
     535              :     pub archived_at: NaiveDateTime,
     536              : 
     537              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     538              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     539              :     pub delete_progress: TimelineDeleteProgress,
     540              : 
     541              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     542              :     pub deleted_from_ancestor: AtomicBool,
     543              : }
     544              : 
     545              : impl OffloadedTimeline {
     546              :     /// Obtains an offloaded timeline from a given timeline object.
     547              :     ///
     548              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     549              :     /// the timeline is not in a stopped state.
     550              :     /// Panics if the timeline is not archived.
     551            1 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     552            1 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     553            1 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     554            1 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     555            1 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     556            1 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     557            1 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     558            1 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     559              :             } else {
     560            0 :                 (None, None)
     561              :             };
     562            1 :         let archived_at = timeline
     563            1 :             .remote_client
     564            1 :             .archived_at_stopped_queue()?
     565            1 :             .expect("must be called on an archived timeline");
     566            1 :         Ok(Self {
     567            1 :             tenant_shard_id: timeline.tenant_shard_id,
     568            1 :             timeline_id: timeline.timeline_id,
     569            1 :             ancestor_timeline_id,
     570            1 :             ancestor_retain_lsn,
     571            1 :             archived_at,
     572            1 : 
     573            1 :             delete_progress: timeline.delete_progress.clone(),
     574            1 :             deleted_from_ancestor: AtomicBool::new(false),
     575            1 :         })
     576            1 :     }
     577            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     578            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     579            0 :         // by the `initialize_gc_info` function.
     580            0 :         let OffloadedTimelineManifest {
     581            0 :             timeline_id,
     582            0 :             ancestor_timeline_id,
     583            0 :             ancestor_retain_lsn,
     584            0 :             archived_at,
     585            0 :         } = *manifest;
     586            0 :         Self {
     587            0 :             tenant_shard_id,
     588            0 :             timeline_id,
     589            0 :             ancestor_timeline_id,
     590            0 :             ancestor_retain_lsn,
     591            0 :             archived_at,
     592            0 :             delete_progress: TimelineDeleteProgress::default(),
     593            0 :             deleted_from_ancestor: AtomicBool::new(false),
     594            0 :         }
     595            0 :     }
     596            1 :     fn manifest(&self) -> OffloadedTimelineManifest {
     597            1 :         let Self {
     598            1 :             timeline_id,
     599            1 :             ancestor_timeline_id,
     600            1 :             ancestor_retain_lsn,
     601            1 :             archived_at,
     602            1 :             ..
     603            1 :         } = self;
     604            1 :         OffloadedTimelineManifest {
     605            1 :             timeline_id: *timeline_id,
     606            1 :             ancestor_timeline_id: *ancestor_timeline_id,
     607            1 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     608            1 :             archived_at: *archived_at,
     609            1 :         }
     610            1 :     }
     611              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     612            0 :     fn delete_from_ancestor_with_timelines(
     613            0 :         &self,
     614            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     615            0 :     ) {
     616            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     617            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     618              :         {
     619            0 :             if let Some((_, ancestor_timeline)) = timelines
     620            0 :                 .iter()
     621            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     622              :             {
     623            0 :                 let removal_happened = ancestor_timeline
     624            0 :                     .gc_info
     625            0 :                     .write()
     626            0 :                     .unwrap()
     627            0 :                     .remove_child_offloaded(self.timeline_id);
     628            0 :                 if !removal_happened {
     629            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     630            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     631            0 :                 }
     632            0 :             }
     633            0 :         }
     634            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     635            0 :     }
     636              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     637              :     ///
     638              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     639            1 :     fn defuse_for_tenant_drop(&self) {
     640            1 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     641            1 :     }
     642              : }
     643              : 
     644              : impl fmt::Debug for OffloadedTimeline {
     645            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     646            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     647            0 :     }
     648              : }
     649              : 
     650              : impl Drop for OffloadedTimeline {
     651            1 :     fn drop(&mut self) {
     652            1 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     653            0 :             tracing::warn!(
     654            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     655              :                 self.timeline_id
     656              :             );
     657            1 :         }
     658            1 :     }
     659              : }
     660              : 
     661              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     662              : pub enum MaybeOffloaded {
     663              :     Yes,
     664              :     No,
     665              : }
     666              : 
     667              : #[derive(Clone, Debug)]
     668              : pub enum TimelineOrOffloaded {
     669              :     Timeline(Arc<Timeline>),
     670              :     Offloaded(Arc<OffloadedTimeline>),
     671              : }
     672              : 
     673              : impl TimelineOrOffloaded {
     674            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     675            0 :         match self {
     676            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     677            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     678              :             }
     679            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     680            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     681              :             }
     682              :         }
     683            0 :     }
     684            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     685            0 :         self.arc_ref().tenant_shard_id()
     686            0 :     }
     687            0 :     pub fn timeline_id(&self) -> TimelineId {
     688            0 :         self.arc_ref().timeline_id()
     689            0 :     }
     690            1 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     691            1 :         match self {
     692            1 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     693            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     694              :         }
     695            1 :     }
     696            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     697            0 :         match self {
     698            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     699            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     700              :         }
     701            0 :     }
     702              : }
     703              : 
     704              : pub enum TimelineOrOffloadedArcRef<'a> {
     705              :     Timeline(&'a Arc<Timeline>),
     706              :     Offloaded(&'a Arc<OffloadedTimeline>),
     707              : }
     708              : 
     709              : impl TimelineOrOffloadedArcRef<'_> {
     710            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     711            0 :         match self {
     712            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     713            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     714              :         }
     715            0 :     }
     716            0 :     pub fn timeline_id(&self) -> TimelineId {
     717            0 :         match self {
     718            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     719            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     720              :         }
     721            0 :     }
     722              : }
     723              : 
     724              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     725            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     726            0 :         Self::Timeline(timeline)
     727            0 :     }
     728              : }
     729              : 
     730              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     731            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     732            0 :         Self::Offloaded(timeline)
     733            0 :     }
     734              : }
     735              : 
     736              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     737              : pub enum GetTimelineError {
     738              :     #[error("Timeline is shutting down")]
     739              :     ShuttingDown,
     740              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     741              :     NotActive {
     742              :         tenant_id: TenantShardId,
     743              :         timeline_id: TimelineId,
     744              :         state: TimelineState,
     745              :     },
     746              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     747              :     NotFound {
     748              :         tenant_id: TenantShardId,
     749              :         timeline_id: TimelineId,
     750              :     },
     751              : }
     752              : 
     753              : #[derive(Debug, thiserror::Error)]
     754              : pub enum LoadLocalTimelineError {
     755              :     #[error("FailedToLoad")]
     756              :     Load(#[source] anyhow::Error),
     757              :     #[error("FailedToResumeDeletion")]
     758              :     ResumeDeletion(#[source] anyhow::Error),
     759              : }
     760              : 
     761              : #[derive(thiserror::Error)]
     762              : pub enum DeleteTimelineError {
     763              :     #[error("NotFound")]
     764              :     NotFound,
     765              : 
     766              :     #[error("HasChildren")]
     767              :     HasChildren(Vec<TimelineId>),
     768              : 
     769              :     #[error("Timeline deletion is already in progress")]
     770              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     771              : 
     772              :     #[error("Cancelled")]
     773              :     Cancelled,
     774              : 
     775              :     #[error(transparent)]
     776              :     Other(#[from] anyhow::Error),
     777              : }
     778              : 
     779              : impl Debug for DeleteTimelineError {
     780            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     781            0 :         match self {
     782            0 :             Self::NotFound => write!(f, "NotFound"),
     783            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     784            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     785            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     786            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     787              :         }
     788            0 :     }
     789              : }
     790              : 
     791              : #[derive(thiserror::Error)]
     792              : pub enum TimelineArchivalError {
     793              :     #[error("NotFound")]
     794              :     NotFound,
     795              : 
     796              :     #[error("Timeout")]
     797              :     Timeout,
     798              : 
     799              :     #[error("Cancelled")]
     800              :     Cancelled,
     801              : 
     802              :     #[error("ancestor is archived: {}", .0)]
     803              :     HasArchivedParent(TimelineId),
     804              : 
     805              :     #[error("HasUnarchivedChildren")]
     806              :     HasUnarchivedChildren(Vec<TimelineId>),
     807              : 
     808              :     #[error("Timeline archival is already in progress")]
     809              :     AlreadyInProgress,
     810              : 
     811              :     #[error(transparent)]
     812              :     Other(anyhow::Error),
     813              : }
     814              : 
     815              : #[derive(thiserror::Error, Debug)]
     816              : pub(crate) enum TenantManifestError {
     817              :     #[error("Remote storage error: {0}")]
     818              :     RemoteStorage(anyhow::Error),
     819              : 
     820              :     #[error("Cancelled")]
     821              :     Cancelled,
     822              : }
     823              : 
     824              : impl From<TenantManifestError> for TimelineArchivalError {
     825            0 :     fn from(e: TenantManifestError) -> Self {
     826            0 :         match e {
     827            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     828            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     829              :         }
     830            0 :     }
     831              : }
     832              : 
     833              : impl Debug for TimelineArchivalError {
     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::Timeout => write!(f, "Timeout"),
     838            0 :             Self::Cancelled => write!(f, "Cancelled"),
     839            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     840            0 :             Self::HasUnarchivedChildren(c) => {
     841            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     842              :             }
     843            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     844            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     845              :         }
     846            0 :     }
     847              : }
     848              : 
     849              : pub enum SetStoppingError {
     850              :     AlreadyStopping(completion::Barrier),
     851              :     Broken,
     852              : }
     853              : 
     854              : impl Debug for SetStoppingError {
     855            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     856            0 :         match self {
     857            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     858            0 :             Self::Broken => write!(f, "Broken"),
     859              :         }
     860            0 :     }
     861              : }
     862              : 
     863              : /// Arguments to [`TenantShard::create_timeline`].
     864              : ///
     865              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     866              : /// is `None`, the result of the timeline create call is not deterministic.
     867              : ///
     868              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     869              : #[derive(Debug)]
     870              : pub(crate) enum CreateTimelineParams {
     871              :     Bootstrap(CreateTimelineParamsBootstrap),
     872              :     Branch(CreateTimelineParamsBranch),
     873              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     874              : }
     875              : 
     876              : #[derive(Debug)]
     877              : pub(crate) struct CreateTimelineParamsBootstrap {
     878              :     pub(crate) new_timeline_id: TimelineId,
     879              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     880              :     pub(crate) pg_version: u32,
     881              : }
     882              : 
     883              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     884              : #[derive(Debug)]
     885              : pub(crate) struct CreateTimelineParamsBranch {
     886              :     pub(crate) new_timeline_id: TimelineId,
     887              :     pub(crate) ancestor_timeline_id: TimelineId,
     888              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     889              : }
     890              : 
     891              : #[derive(Debug)]
     892              : pub(crate) struct CreateTimelineParamsImportPgdata {
     893              :     pub(crate) new_timeline_id: TimelineId,
     894              :     pub(crate) location: import_pgdata::index_part_format::Location,
     895              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     896              : }
     897              : 
     898              : /// What is used to determine idempotency of a [`TenantShard::create_timeline`] call in  [`TenantShard::start_creating_timeline`] in  [`TenantShard::start_creating_timeline`].
     899              : ///
     900              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     901              : ///
     902              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     903              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     904              : ///
     905              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     906              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     907              : ///
     908              : /// Notes:
     909              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     910              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     911              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     912              : ///
     913              : #[derive(Debug, Clone, PartialEq, Eq)]
     914              : pub(crate) enum CreateTimelineIdempotency {
     915              :     /// NB: special treatment, see comment in [`Self`].
     916              :     FailWithConflict,
     917              :     Bootstrap {
     918              :         pg_version: u32,
     919              :     },
     920              :     /// NB: branches always have the same `pg_version` as their ancestor.
     921              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     922              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     923              :     /// determining the child branch pg_version.
     924              :     Branch {
     925              :         ancestor_timeline_id: TimelineId,
     926              :         ancestor_start_lsn: Lsn,
     927              :     },
     928              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     929              : }
     930              : 
     931              : #[derive(Debug, Clone, PartialEq, Eq)]
     932              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     933              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     934              : }
     935              : 
     936              : /// What is returned by [`TenantShard::start_creating_timeline`].
     937              : #[must_use]
     938              : enum StartCreatingTimelineResult {
     939              :     CreateGuard(TimelineCreateGuard),
     940              :     Idempotent(Arc<Timeline>),
     941              : }
     942              : 
     943              : #[allow(clippy::large_enum_variant, reason = "TODO")]
     944              : enum TimelineInitAndSyncResult {
     945              :     ReadyToActivate,
     946              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     947              : }
     948              : 
     949              : #[must_use]
     950              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     951              :     timeline: Arc<Timeline>,
     952              :     import_pgdata: import_pgdata::index_part_format::Root,
     953              :     guard: TimelineCreateGuard,
     954              : }
     955              : 
     956              : /// What is returned by [`TenantShard::create_timeline`].
     957              : enum CreateTimelineResult {
     958              :     Created(Arc<Timeline>),
     959              :     Idempotent(Arc<Timeline>),
     960              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`TenantShard::timelines`] when
     961              :     /// we return this result, nor will this concrete object ever be added there.
     962              :     /// Cf method comment on [`TenantShard::create_timeline_import_pgdata`].
     963              :     ImportSpawned(Arc<Timeline>),
     964              : }
     965              : 
     966              : impl CreateTimelineResult {
     967            0 :     fn discriminant(&self) -> &'static str {
     968            0 :         match self {
     969            0 :             Self::Created(_) => "Created",
     970            0 :             Self::Idempotent(_) => "Idempotent",
     971            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     972              :         }
     973            0 :     }
     974            0 :     fn timeline(&self) -> &Arc<Timeline> {
     975            0 :         match self {
     976            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     977            0 :         }
     978            0 :     }
     979              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     980              :     #[cfg(test)]
     981          118 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     982          118 :         match self {
     983          118 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     984          118 :         }
     985          118 :     }
     986              : }
     987              : 
     988              : #[derive(thiserror::Error, Debug)]
     989              : pub enum CreateTimelineError {
     990              :     #[error("creation of timeline with the given ID is in progress")]
     991              :     AlreadyCreating,
     992              :     #[error("timeline already exists with different parameters")]
     993              :     Conflict,
     994              :     #[error(transparent)]
     995              :     AncestorLsn(anyhow::Error),
     996              :     #[error("ancestor timeline is not active")]
     997              :     AncestorNotActive,
     998              :     #[error("ancestor timeline is archived")]
     999              :     AncestorArchived,
    1000              :     #[error("tenant shutting down")]
    1001              :     ShuttingDown,
    1002              :     #[error(transparent)]
    1003              :     Other(#[from] anyhow::Error),
    1004              : }
    1005              : 
    1006              : #[derive(thiserror::Error, Debug)]
    1007              : pub enum InitdbError {
    1008              :     #[error("Operation was cancelled")]
    1009              :     Cancelled,
    1010              :     #[error(transparent)]
    1011              :     Other(anyhow::Error),
    1012              :     #[error(transparent)]
    1013              :     Inner(postgres_initdb::Error),
    1014              : }
    1015              : 
    1016              : enum CreateTimelineCause {
    1017              :     Load,
    1018              :     Delete,
    1019              : }
    1020              : 
    1021              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1022              : enum LoadTimelineCause {
    1023              :     Attach,
    1024              :     Unoffload,
    1025              : }
    1026              : 
    1027              : #[derive(thiserror::Error, Debug)]
    1028              : pub(crate) enum GcError {
    1029              :     // The tenant is shutting down
    1030              :     #[error("tenant shutting down")]
    1031              :     TenantCancelled,
    1032              : 
    1033              :     // The tenant is shutting down
    1034              :     #[error("timeline shutting down")]
    1035              :     TimelineCancelled,
    1036              : 
    1037              :     // The tenant is in a state inelegible to run GC
    1038              :     #[error("not active")]
    1039              :     NotActive,
    1040              : 
    1041              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1042              :     #[error("not active")]
    1043              :     BadLsn { why: String },
    1044              : 
    1045              :     // A remote storage error while scheduling updates after compaction
    1046              :     #[error(transparent)]
    1047              :     Remote(anyhow::Error),
    1048              : 
    1049              :     // An error reading while calculating GC cutoffs
    1050              :     #[error(transparent)]
    1051              :     GcCutoffs(PageReconstructError),
    1052              : 
    1053              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1054              :     #[error("timeline not found")]
    1055              :     TimelineNotFound,
    1056              : }
    1057              : 
    1058              : impl From<PageReconstructError> for GcError {
    1059            0 :     fn from(value: PageReconstructError) -> Self {
    1060            0 :         match value {
    1061            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1062            0 :             other => Self::GcCutoffs(other),
    1063              :         }
    1064            0 :     }
    1065              : }
    1066              : 
    1067              : impl From<NotInitialized> for GcError {
    1068            0 :     fn from(value: NotInitialized) -> Self {
    1069            0 :         match value {
    1070            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1071            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1072              :         }
    1073            0 :     }
    1074              : }
    1075              : 
    1076              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1077            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1078            0 :         GcError::TimelineCancelled
    1079            0 :     }
    1080              : }
    1081              : 
    1082              : #[derive(thiserror::Error, Debug)]
    1083              : pub(crate) enum LoadConfigError {
    1084              :     #[error("TOML deserialization error: '{0}'")]
    1085              :     DeserializeToml(#[from] toml_edit::de::Error),
    1086              : 
    1087              :     #[error("Config not found at {0}")]
    1088              :     NotFound(Utf8PathBuf),
    1089              : }
    1090              : 
    1091              : impl TenantShard {
    1092              :     /// Yet another helper for timeline initialization.
    1093              :     ///
    1094              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1095              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1096              :     /// - Downloads remote index file and adds remote files to the layer map
    1097              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1098              :     ///
    1099              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1100              :     /// it is marked as Active.
    1101              :     #[allow(clippy::too_many_arguments)]
    1102            3 :     async fn timeline_init_and_sync(
    1103            3 :         self: &Arc<Self>,
    1104            3 :         timeline_id: TimelineId,
    1105            3 :         resources: TimelineResources,
    1106            3 :         index_part: IndexPart,
    1107            3 :         metadata: TimelineMetadata,
    1108            3 :         previous_heatmap: Option<PreviousHeatmap>,
    1109            3 :         ancestor: Option<Arc<Timeline>>,
    1110            3 :         cause: LoadTimelineCause,
    1111            3 :         ctx: &RequestContext,
    1112            3 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1113            3 :         let tenant_id = self.tenant_shard_id;
    1114            3 : 
    1115            3 :         let import_pgdata = index_part.import_pgdata.clone();
    1116            3 :         let idempotency = match &import_pgdata {
    1117            0 :             Some(import_pgdata) => {
    1118            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1119            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1120            0 :                 })
    1121              :             }
    1122              :             None => {
    1123            3 :                 if metadata.ancestor_timeline().is_none() {
    1124            2 :                     CreateTimelineIdempotency::Bootstrap {
    1125            2 :                         pg_version: metadata.pg_version(),
    1126            2 :                     }
    1127              :                 } else {
    1128            1 :                     CreateTimelineIdempotency::Branch {
    1129            1 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1130            1 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1131            1 :                     }
    1132              :                 }
    1133              :             }
    1134              :         };
    1135              : 
    1136            3 :         let (timeline, _timeline_ctx) = self.create_timeline_struct(
    1137            3 :             timeline_id,
    1138            3 :             &metadata,
    1139            3 :             previous_heatmap,
    1140            3 :             ancestor.clone(),
    1141            3 :             resources,
    1142            3 :             CreateTimelineCause::Load,
    1143            3 :             idempotency.clone(),
    1144            3 :             index_part.gc_compaction.clone(),
    1145            3 :             index_part.rel_size_migration.clone(),
    1146            3 :             ctx,
    1147            3 :         )?;
    1148            3 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1149            3 :         anyhow::ensure!(
    1150            3 :             disk_consistent_lsn.is_valid(),
    1151            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1152              :         );
    1153            3 :         assert_eq!(
    1154            3 :             disk_consistent_lsn,
    1155            3 :             metadata.disk_consistent_lsn(),
    1156            0 :             "these are used interchangeably"
    1157              :         );
    1158              : 
    1159            3 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1160              : 
    1161            3 :         timeline
    1162            3 :             .load_layer_map(disk_consistent_lsn, index_part)
    1163            3 :             .await
    1164            3 :             .with_context(|| {
    1165            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1166            3 :             })?;
    1167              : 
    1168              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1169              :         // to the archival operation. To allow warming this timeline up, generate
    1170              :         // a previous heatmap which contains all visible layers in the layer map.
    1171              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1172              :         // for the timeline.
    1173            3 :         if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
    1174            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1175            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1176            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1177              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1178              :                 // If the current branch point greater than the previous one use the the heatmap
    1179              :                 // we just generated - it should include more layers.
    1180            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1181            0 :                     tline
    1182            0 :                         .previous_heatmap
    1183            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1184            0 :                 } else {
    1185            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1186              :                 }
    1187              : 
    1188            0 :                 match tline.ancestor_timeline() {
    1189            0 :                     Some(ancestor) => {
    1190            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1191              :                             // Ancestor timeline is shutting down.
    1192            0 :                             break;
    1193            0 :                         }
    1194            0 : 
    1195            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1196              :                     }
    1197            0 :                     None => {
    1198            0 :                         tline_ending_at = None;
    1199            0 :                     }
    1200              :                 }
    1201              :             }
    1202            3 :         }
    1203              : 
    1204            0 :         match import_pgdata {
    1205            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1206            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1207            0 :                 if !guard.insert(timeline_id) {
    1208              :                     // We should never try and load the same timeline twice during startup
    1209            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1210            0 :                 }
    1211            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1212            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1213            0 :                     owning_tenant: self.clone(),
    1214            0 :                     timeline_id,
    1215            0 :                     idempotency,
    1216            0 :                     // The users of this specific return value don't need the timline_path in there.
    1217            0 :                     timeline_path: timeline
    1218            0 :                         .conf
    1219            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1220            0 :                 };
    1221            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1222            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1223            0 :                         timeline,
    1224            0 :                         import_pgdata,
    1225            0 :                         guard: timeline_create_guard,
    1226            0 :                     },
    1227            0 :                 ))
    1228              :             }
    1229              :             Some(_) | None => {
    1230              :                 {
    1231            3 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1232            3 :                     match timelines_accessor.entry(timeline_id) {
    1233              :                         // We should never try and load the same timeline twice during startup
    1234              :                         Entry::Occupied(_) => {
    1235            0 :                             unreachable!(
    1236            0 :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1237            0 :                             );
    1238              :                         }
    1239            3 :                         Entry::Vacant(v) => {
    1240            3 :                             v.insert(Arc::clone(&timeline));
    1241            3 :                             timeline.maybe_spawn_flush_loop();
    1242            3 :                         }
    1243              :                     }
    1244              :                 }
    1245              : 
    1246              :                 // Sanity check: a timeline should have some content.
    1247            3 :                 anyhow::ensure!(
    1248            3 :                     ancestor.is_some()
    1249            2 :                         || timeline
    1250            2 :                             .layers
    1251            2 :                             .read()
    1252            2 :                             .await
    1253            2 :                             .layer_map()
    1254            2 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1255            2 :                             .iter_historic_layers()
    1256            2 :                             .next()
    1257            2 :                             .is_some(),
    1258            0 :                     "Timeline has no ancestor and no layer files"
    1259              :                 );
    1260              : 
    1261            3 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate)
    1262              :             }
    1263              :         }
    1264            3 :     }
    1265              : 
    1266              :     /// Attach a tenant that's available in cloud storage.
    1267              :     ///
    1268              :     /// This returns quickly, after just creating the in-memory object
    1269              :     /// Tenant struct and launching a background task to download
    1270              :     /// the remote index files.  On return, the tenant is most likely still in
    1271              :     /// Attaching state, and it will become Active once the background task
    1272              :     /// finishes. You can use wait_until_active() to wait for the task to
    1273              :     /// complete.
    1274              :     ///
    1275              :     #[allow(clippy::too_many_arguments)]
    1276            0 :     pub(crate) fn spawn(
    1277            0 :         conf: &'static PageServerConf,
    1278            0 :         tenant_shard_id: TenantShardId,
    1279            0 :         resources: TenantSharedResources,
    1280            0 :         attached_conf: AttachedTenantConf,
    1281            0 :         shard_identity: ShardIdentity,
    1282            0 :         init_order: Option<InitializationOrder>,
    1283            0 :         mode: SpawnMode,
    1284            0 :         ctx: &RequestContext,
    1285            0 :     ) -> Result<Arc<TenantShard>, GlobalShutDown> {
    1286            0 :         let wal_redo_manager =
    1287            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1288              : 
    1289              :         let TenantSharedResources {
    1290            0 :             broker_client,
    1291            0 :             remote_storage,
    1292            0 :             deletion_queue_client,
    1293            0 :             l0_flush_global_state,
    1294            0 :             basebackup_prepare_sender,
    1295            0 :         } = resources;
    1296            0 : 
    1297            0 :         let attach_mode = attached_conf.location.attach_mode;
    1298            0 :         let generation = attached_conf.location.generation;
    1299            0 : 
    1300            0 :         let tenant = Arc::new(TenantShard::new(
    1301            0 :             TenantState::Attaching,
    1302            0 :             conf,
    1303            0 :             attached_conf,
    1304            0 :             shard_identity,
    1305            0 :             Some(wal_redo_manager),
    1306            0 :             tenant_shard_id,
    1307            0 :             remote_storage.clone(),
    1308            0 :             deletion_queue_client,
    1309            0 :             l0_flush_global_state,
    1310            0 :             basebackup_prepare_sender,
    1311            0 :         ));
    1312            0 : 
    1313            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1314            0 :         // we shut down while attaching.
    1315            0 :         let attach_gate_guard = tenant
    1316            0 :             .gate
    1317            0 :             .enter()
    1318            0 :             .expect("We just created the TenantShard: nothing else can have shut it down yet");
    1319            0 : 
    1320            0 :         // Do all the hard work in the background
    1321            0 :         let tenant_clone = Arc::clone(&tenant);
    1322            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1323            0 :         task_mgr::spawn(
    1324            0 :             &tokio::runtime::Handle::current(),
    1325            0 :             TaskKind::Attach,
    1326            0 :             tenant_shard_id,
    1327            0 :             None,
    1328            0 :             "attach tenant",
    1329            0 :             async move {
    1330            0 : 
    1331            0 :                 info!(
    1332              :                     ?attach_mode,
    1333            0 :                     "Attaching tenant"
    1334              :                 );
    1335              : 
    1336            0 :                 let _gate_guard = attach_gate_guard;
    1337            0 : 
    1338            0 :                 // Is this tenant being spawned as part of process startup?
    1339            0 :                 let starting_up = init_order.is_some();
    1340            0 :                 scopeguard::defer! {
    1341            0 :                     if starting_up {
    1342            0 :                         TENANT.startup_complete.inc();
    1343            0 :                     }
    1344            0 :                 }
    1345              : 
    1346            0 :                 fn make_broken_or_stopping(t: &TenantShard, err: anyhow::Error) {
    1347            0 :                     t.state.send_modify(|state| match state {
    1348              :                         // TODO: the old code alluded to DeleteTenantFlow sometimes setting
    1349              :                         // TenantState::Stopping before we get here, but this may be outdated.
    1350              :                         // Let's find out with a testing assertion. If this doesn't fire, and the
    1351              :                         // logs don't show this happening in production, remove the Stopping cases.
    1352            0 :                         TenantState::Stopping{..} if cfg!(any(test, feature = "testing")) => {
    1353            0 :                             panic!("unexpected TenantState::Stopping during attach")
    1354              :                         }
    1355              :                         // If the tenant is cancelled, assume the error was caused by cancellation.
    1356            0 :                         TenantState::Attaching if t.cancel.is_cancelled() => {
    1357            0 :                             info!("attach cancelled, setting tenant state to Stopping: {err}");
    1358              :                             // NB: progress None tells `set_stopping` that attach has cancelled.
    1359            0 :                             *state = TenantState::Stopping { progress: None };
    1360              :                         }
    1361              :                         // According to the old code, DeleteTenantFlow may already have set this to
    1362              :                         // Stopping. Retain its progress.
    1363              :                         // TODO: there is no DeleteTenantFlow. Is this still needed? See above.
    1364            0 :                         TenantState::Stopping { progress } if t.cancel.is_cancelled() => {
    1365            0 :                             assert!(progress.is_some(), "concurrent attach cancellation");
    1366            0 :                             info!("attach cancelled, already Stopping: {err}");
    1367              :                         }
    1368              :                         // Mark the tenant as broken.
    1369              :                         TenantState::Attaching | TenantState::Stopping { .. } => {
    1370            0 :                             error!("attach failed, setting tenant state to Broken (was {state}): {err:?}");
    1371            0 :                             *state = TenantState::broken_from_reason(err.to_string())
    1372              :                         }
    1373              :                         // The attach task owns the tenant state until activated.
    1374            0 :                         state => panic!("invalid tenant state {state} during attach: {err:?}"),
    1375            0 :                     });
    1376            0 :                 }
    1377              : 
    1378              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1379            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1380            0 :                     make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1381            0 :                     return Ok(());
    1382            0 :                 }
    1383            0 : 
    1384            0 :                 let mut init_order = init_order;
    1385            0 :                 // take the completion because initial tenant loading will complete when all of
    1386            0 :                 // these tasks complete.
    1387            0 :                 let _completion = init_order
    1388            0 :                     .as_mut()
    1389            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1390            0 :                 let remote_load_completion = init_order
    1391            0 :                     .as_mut()
    1392            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1393              : 
    1394              :                 enum AttachType<'a> {
    1395              :                     /// We are attaching this tenant lazily in the background.
    1396              :                     Warmup {
    1397              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1398              :                         during_startup: bool
    1399              :                     },
    1400              :                     /// We are attaching this tenant as soon as we can, because for example an
    1401              :                     /// endpoint tried to access it.
    1402              :                     OnDemand,
    1403              :                     /// During normal operations after startup, we are attaching a tenant, and
    1404              :                     /// eager attach was requested.
    1405              :                     Normal,
    1406              :                 }
    1407              : 
    1408            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1409              :                     // Before doing any I/O, wait for at least one of:
    1410              :                     // - A client attempting to access to this tenant (on-demand loading)
    1411              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1412              : 
    1413            0 :                     tokio::select!(
    1414            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1415            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1416            0 :                             tracing::info!("Activating tenant (on-demand)");
    1417            0 :                             AttachType::OnDemand
    1418              :                         },
    1419            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1420            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1421            0 :                             tracing::info!("Activating tenant (warmup)");
    1422            0 :                             AttachType::Warmup {
    1423            0 :                                 _permit,
    1424            0 :                                 during_startup: init_order.is_some()
    1425            0 :                             }
    1426              :                         }
    1427            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1428              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1429              :                             // stayed in Activating for such a long time that shutdown found it in
    1430              :                             // that state.
    1431            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1432              :                             // Set the tenant to Stopping to signal `set_stopping` that we're done.
    1433            0 :                             make_broken_or_stopping(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"));
    1434            0 :                             return Ok(());
    1435              :                         },
    1436              :                     )
    1437              :                 } else {
    1438              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1439              :                     // concurrent_tenant_warmup queue
    1440            0 :                     AttachType::Normal
    1441              :                 };
    1442              : 
    1443            0 :                 let preload = match &mode {
    1444              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1445            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1446            0 :                         let res = tenant_clone
    1447            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1448            0 :                             .await;
    1449            0 :                         match res {
    1450            0 :                             Ok(p) => Some(p),
    1451            0 :                             Err(e) => {
    1452            0 :                                 make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1453            0 :                                 return Ok(());
    1454              :                             }
    1455              :                         }
    1456              :                     }
    1457              : 
    1458              :                 };
    1459              : 
    1460              :                 // Remote preload is complete.
    1461            0 :                 drop(remote_load_completion);
    1462            0 : 
    1463            0 : 
    1464            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1465            0 :                 let attach_start = std::time::Instant::now();
    1466            0 :                 let attached = {
    1467            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1468            0 :                     tenant_clone.attach(preload, &ctx).await
    1469              :                 };
    1470            0 :                 let attach_duration = attach_start.elapsed();
    1471            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1472            0 : 
    1473            0 :                 match attached {
    1474              :                     Ok(()) => {
    1475            0 :                         info!("attach finished, activating");
    1476            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1477              :                     }
    1478            0 :                     Err(e) => make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e)),
    1479              :                 }
    1480              : 
    1481              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1482              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1483              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1484              :                 //
    1485              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1486              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1487              :                 // then warmup will wait for that before proceeding to the next tenant.
    1488            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1489            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1490            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1491            0 :                     while futs.next().await.is_some() {}
    1492            0 :                     tracing::info!("Warm-up complete");
    1493            0 :                 }
    1494              : 
    1495            0 :                 Ok(())
    1496            0 :             }
    1497            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1498              :         );
    1499            0 :         Ok(tenant)
    1500            0 :     }
    1501              : 
    1502              :     #[instrument(skip_all)]
    1503              :     pub(crate) async fn preload(
    1504              :         self: &Arc<Self>,
    1505              :         remote_storage: &GenericRemoteStorage,
    1506              :         cancel: CancellationToken,
    1507              :     ) -> anyhow::Result<TenantPreload> {
    1508              :         span::debug_assert_current_span_has_tenant_id();
    1509              :         // Get list of remote timelines
    1510              :         // download index files for every tenant timeline
    1511              :         info!("listing remote timelines");
    1512              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1513              :             remote_storage,
    1514              :             self.tenant_shard_id,
    1515              :             cancel.clone(),
    1516              :         )
    1517              :         .await?;
    1518              : 
    1519              :         let tenant_manifest = match download_tenant_manifest(
    1520              :             remote_storage,
    1521              :             &self.tenant_shard_id,
    1522              :             self.generation,
    1523              :             &cancel,
    1524              :         )
    1525              :         .await
    1526              :         {
    1527              :             Ok((tenant_manifest, _, _)) => Some(tenant_manifest),
    1528              :             Err(DownloadError::NotFound) => None,
    1529              :             Err(err) => return Err(err.into()),
    1530              :         };
    1531              : 
    1532              :         info!(
    1533              :             "found {} timelines ({} offloaded timelines)",
    1534              :             remote_timeline_ids.len(),
    1535              :             tenant_manifest
    1536              :                 .as_ref()
    1537            3 :                 .map(|m| m.offloaded_timelines.len())
    1538              :                 .unwrap_or(0)
    1539              :         );
    1540              : 
    1541              :         for k in other_keys {
    1542              :             warn!("Unexpected non timeline key {k}");
    1543              :         }
    1544              : 
    1545              :         // Avoid downloading IndexPart of offloaded timelines.
    1546              :         let mut offloaded_with_prefix = HashSet::new();
    1547              :         if let Some(tenant_manifest) = &tenant_manifest {
    1548              :             for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1549              :                 if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1550              :                     offloaded_with_prefix.insert(offloaded.timeline_id);
    1551              :                 } else {
    1552              :                     // We'll take care later of timelines in the manifest without a prefix
    1553              :                 }
    1554              :             }
    1555              :         }
    1556              : 
    1557              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1558              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1559              :         // will kick the secondary in any case and cause a download.
    1560              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1561              : 
    1562              :         let timelines = self
    1563              :             .load_timelines_metadata(
    1564              :                 remote_timeline_ids,
    1565              :                 remote_storage,
    1566              :                 maybe_heatmap_at,
    1567              :                 cancel,
    1568              :             )
    1569              :             .await?;
    1570              : 
    1571              :         Ok(TenantPreload {
    1572              :             tenant_manifest,
    1573              :             timelines: timelines
    1574              :                 .into_iter()
    1575            3 :                 .map(|(id, tl)| (id, Some(tl)))
    1576            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1577              :                 .collect(),
    1578              :         })
    1579              :     }
    1580              : 
    1581          117 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1582          117 :         if !self.conf.load_previous_heatmap {
    1583            0 :             return None;
    1584          117 :         }
    1585          117 : 
    1586          117 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1587          117 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1588            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1589            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1590            0 :                 Err(err) => {
    1591            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1592            0 :                     None
    1593              :                 }
    1594              :             },
    1595          117 :             Err(err) => match err.kind() {
    1596          117 :                 std::io::ErrorKind::NotFound => None,
    1597              :                 _ => {
    1598            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1599            0 :                     None
    1600              :                 }
    1601              :             },
    1602              :         }
    1603          117 :     }
    1604              : 
    1605              :     ///
    1606              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1607              :     ///
    1608              :     /// No background tasks are started as part of this routine.
    1609              :     ///
    1610          117 :     async fn attach(
    1611          117 :         self: &Arc<TenantShard>,
    1612          117 :         preload: Option<TenantPreload>,
    1613          117 :         ctx: &RequestContext,
    1614          117 :     ) -> anyhow::Result<()> {
    1615          117 :         span::debug_assert_current_span_has_tenant_id();
    1616          117 : 
    1617          117 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1618              : 
    1619          117 :         let Some(preload) = preload else {
    1620            0 :             anyhow::bail!(
    1621            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1622            0 :             );
    1623              :         };
    1624              : 
    1625          117 :         let mut offloaded_timeline_ids = HashSet::new();
    1626          117 :         let mut offloaded_timelines_list = Vec::new();
    1627          117 :         if let Some(tenant_manifest) = &preload.tenant_manifest {
    1628            3 :             for timeline_manifest in tenant_manifest.offloaded_timelines.iter() {
    1629            0 :                 let timeline_id = timeline_manifest.timeline_id;
    1630            0 :                 let offloaded_timeline =
    1631            0 :                     OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1632            0 :                 offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1633            0 :                 offloaded_timeline_ids.insert(timeline_id);
    1634            0 :             }
    1635          114 :         }
    1636              :         // Complete deletions for offloaded timeline id's from manifest.
    1637              :         // The manifest will be uploaded later in this function.
    1638          117 :         offloaded_timelines_list
    1639          117 :             .retain(|(offloaded_id, offloaded)| {
    1640            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1641            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1642            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1643            0 :                 if delete {
    1644            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1645            0 :                     offloaded.defuse_for_tenant_drop();
    1646            0 :                 }
    1647            0 :                 !delete
    1648          117 :         });
    1649          117 : 
    1650          117 :         let mut timelines_to_resume_deletions = vec![];
    1651          117 : 
    1652          117 :         let mut remote_index_and_client = HashMap::new();
    1653          117 :         let mut timeline_ancestors = HashMap::new();
    1654          117 :         let mut existent_timelines = HashSet::new();
    1655          120 :         for (timeline_id, preload) in preload.timelines {
    1656            3 :             let Some(preload) = preload else { continue };
    1657              :             // This is an invariant of the `preload` function's API
    1658            3 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1659            3 :             let index_part = match preload.index_part {
    1660            3 :                 Ok(i) => {
    1661            3 :                     debug!("remote index part exists for timeline {timeline_id}");
    1662              :                     // We found index_part on the remote, this is the standard case.
    1663            3 :                     existent_timelines.insert(timeline_id);
    1664            3 :                     i
    1665              :                 }
    1666              :                 Err(DownloadError::NotFound) => {
    1667              :                     // There is no index_part on the remote. We only get here
    1668              :                     // if there is some prefix for the timeline in the remote storage.
    1669              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1670              :                     // remnant from a prior incomplete creation or deletion attempt.
    1671              :                     // Delete the local directory as the deciding criterion for a
    1672              :                     // timeline's existence is presence of index_part.
    1673            0 :                     info!(%timeline_id, "index_part not found on remote");
    1674            0 :                     continue;
    1675              :                 }
    1676            0 :                 Err(DownloadError::Fatal(why)) => {
    1677            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1678            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1679            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1680            0 :                     anyhow::bail!(why.to_string());
    1681              :                 }
    1682            0 :                 Err(e) => {
    1683            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1684            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1685            0 :                     // as it might be a temporary issue and we don't want to re-download
    1686            0 :                     // everything after it resolves.
    1687            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1688              : 
    1689            0 :                     existent_timelines.insert(timeline_id);
    1690            0 :                     continue;
    1691              :                 }
    1692              :             };
    1693            3 :             match index_part {
    1694            3 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1695            3 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1696            3 :                     remote_index_and_client.insert(
    1697            3 :                         timeline_id,
    1698            3 :                         (index_part, preload.client, preload.previous_heatmap),
    1699            3 :                     );
    1700            3 :                 }
    1701            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1702            0 :                     info!(
    1703            0 :                         "timeline {} is deleted, picking to resume deletion",
    1704              :                         timeline_id
    1705              :                     );
    1706            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1707              :                 }
    1708              :             }
    1709              :         }
    1710              : 
    1711          117 :         let mut gc_blocks = HashMap::new();
    1712              : 
    1713              :         // For every timeline, download the metadata file, scan the local directory,
    1714              :         // and build a layer map that contains an entry for each remote and local
    1715              :         // layer file.
    1716          117 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1717          120 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1718            3 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1719            3 :                 .remove(&timeline_id)
    1720            3 :                 .expect("just put it in above");
    1721              : 
    1722            3 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1723              :                 // could just filter these away, but it helps while testing
    1724            0 :                 anyhow::ensure!(
    1725            0 :                     !blocking.reasons.is_empty(),
    1726            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1727              :                 );
    1728            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1729            0 :                 assert!(prev.is_none());
    1730            3 :             }
    1731              : 
    1732              :             // TODO again handle early failure
    1733            3 :             let effect = self
    1734            3 :                 .load_remote_timeline(
    1735            3 :                     timeline_id,
    1736            3 :                     index_part,
    1737            3 :                     remote_metadata,
    1738            3 :                     previous_heatmap,
    1739            3 :                     self.get_timeline_resources_for(remote_client),
    1740            3 :                     LoadTimelineCause::Attach,
    1741            3 :                     ctx,
    1742            3 :                 )
    1743            3 :                 .await
    1744            3 :                 .with_context(|| {
    1745            0 :                     format!(
    1746            0 :                         "failed to load remote timeline {} for tenant {}",
    1747            0 :                         timeline_id, self.tenant_shard_id
    1748            0 :                     )
    1749            3 :                 })?;
    1750              : 
    1751            3 :             match effect {
    1752            3 :                 TimelineInitAndSyncResult::ReadyToActivate => {
    1753            3 :                     // activation happens later, on Tenant::activate
    1754            3 :                 }
    1755              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1756              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1757            0 :                         timeline,
    1758            0 :                         import_pgdata,
    1759            0 :                         guard,
    1760            0 :                     },
    1761            0 :                 ) => {
    1762            0 :                     let timeline_id = timeline.timeline_id;
    1763            0 :                     let import_task_handle =
    1764            0 :                         tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1765            0 :                             timeline.clone(),
    1766            0 :                             import_pgdata,
    1767            0 :                             guard,
    1768            0 :                             ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    1769            0 :                         ));
    1770            0 : 
    1771            0 :                     let prev = self.timelines_importing.lock().unwrap().insert(
    1772            0 :                         timeline_id,
    1773            0 :                         ImportingTimeline {
    1774            0 :                             timeline: timeline.clone(),
    1775            0 :                             import_task_handle,
    1776            0 :                         },
    1777            0 :                     );
    1778            0 : 
    1779            0 :                     assert!(prev.is_none());
    1780              :                 }
    1781              :             }
    1782              :         }
    1783              : 
    1784              :         // Walk through deleted timelines, resume deletion
    1785          117 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1786            0 :             remote_timeline_client
    1787            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1788            0 :                 .context("init queue stopped")
    1789            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1790              : 
    1791            0 :             DeleteTimelineFlow::resume_deletion(
    1792            0 :                 Arc::clone(self),
    1793            0 :                 timeline_id,
    1794            0 :                 &index_part.metadata,
    1795            0 :                 remote_timeline_client,
    1796            0 :                 ctx,
    1797            0 :             )
    1798            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1799            0 :             .await
    1800            0 :             .context("resume_deletion")
    1801            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1802              :         }
    1803          117 :         {
    1804          117 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1805          117 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1806          117 :         }
    1807              : 
    1808              :         // Stash the preloaded tenant manifest, and upload a new manifest if changed.
    1809              :         //
    1810              :         // NB: this must happen after the tenant is fully populated above. In particular the
    1811              :         // offloaded timelines, which are included in the manifest.
    1812              :         {
    1813          117 :             let mut guard = self.remote_tenant_manifest.lock().await;
    1814          117 :             assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
    1815          117 :             *guard = preload.tenant_manifest;
    1816          117 :         }
    1817          117 :         self.maybe_upload_tenant_manifest().await?;
    1818              : 
    1819              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1820              :         // IndexPart is the source of truth.
    1821          117 :         self.clean_up_timelines(&existent_timelines)?;
    1822              : 
    1823          117 :         self.gc_block.set_scanned(gc_blocks);
    1824          117 : 
    1825          117 :         fail::fail_point!("attach-before-activate", |_| {
    1826            0 :             anyhow::bail!("attach-before-activate");
    1827          117 :         });
    1828          117 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1829              : 
    1830          117 :         info!("Done");
    1831              : 
    1832          117 :         Ok(())
    1833          117 :     }
    1834              : 
    1835              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1836              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1837              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1838          117 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1839          117 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1840              : 
    1841          117 :         let entries = match timelines_dir.read_dir_utf8() {
    1842          117 :             Ok(d) => d,
    1843            0 :             Err(e) => {
    1844            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1845            0 :                     return Ok(());
    1846              :                 } else {
    1847            0 :                     return Err(e).context("list timelines directory for tenant");
    1848              :                 }
    1849              :             }
    1850              :         };
    1851              : 
    1852          121 :         for entry in entries {
    1853            4 :             let entry = entry.context("read timeline dir entry")?;
    1854            4 :             let entry_path = entry.path();
    1855              : 
    1856            4 :             let purge = if crate::is_temporary(entry_path) {
    1857            0 :                 true
    1858              :             } else {
    1859            4 :                 match TimelineId::try_from(entry_path.file_name()) {
    1860            4 :                     Ok(i) => {
    1861            4 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1862            4 :                         !existent_timelines.contains(&i)
    1863              :                     }
    1864            0 :                     Err(e) => {
    1865            0 :                         tracing::warn!(
    1866            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1867              :                         );
    1868              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1869            0 :                         false
    1870              :                     }
    1871              :                 }
    1872              :             };
    1873              : 
    1874            4 :             if purge {
    1875            1 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1876            1 :                 if let Err(e) = match entry.file_type() {
    1877            1 :                     Ok(t) => if t.is_dir() {
    1878            1 :                         std::fs::remove_dir_all(entry_path)
    1879              :                     } else {
    1880            0 :                         std::fs::remove_file(entry_path)
    1881              :                     }
    1882            1 :                     .or_else(fs_ext::ignore_not_found),
    1883            0 :                     Err(e) => Err(e),
    1884              :                 } {
    1885            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1886            1 :                 }
    1887            3 :             }
    1888              :         }
    1889              : 
    1890          117 :         Ok(())
    1891          117 :     }
    1892              : 
    1893              :     /// Get sum of all remote timelines sizes
    1894              :     ///
    1895              :     /// This function relies on the index_part instead of listing the remote storage
    1896            0 :     pub fn remote_size(&self) -> u64 {
    1897            0 :         let mut size = 0;
    1898              : 
    1899            0 :         for timeline in self.list_timelines() {
    1900            0 :             size += timeline.remote_client.get_remote_physical_size();
    1901            0 :         }
    1902              : 
    1903            0 :         size
    1904            0 :     }
    1905              : 
    1906              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1907              :     #[allow(clippy::too_many_arguments)]
    1908              :     async fn load_remote_timeline(
    1909              :         self: &Arc<Self>,
    1910              :         timeline_id: TimelineId,
    1911              :         index_part: IndexPart,
    1912              :         remote_metadata: TimelineMetadata,
    1913              :         previous_heatmap: Option<PreviousHeatmap>,
    1914              :         resources: TimelineResources,
    1915              :         cause: LoadTimelineCause,
    1916              :         ctx: &RequestContext,
    1917              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1918              :         span::debug_assert_current_span_has_tenant_id();
    1919              : 
    1920              :         info!("downloading index file for timeline {}", timeline_id);
    1921              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1922              :             .await
    1923              :             .context("Failed to create new timeline directory")?;
    1924              : 
    1925              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1926              :             let timelines = self.timelines.lock().unwrap();
    1927              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1928            0 :                 || {
    1929            0 :                     anyhow::anyhow!(
    1930            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1931            0 :                     )
    1932            0 :                 },
    1933              :             )?))
    1934              :         } else {
    1935              :             None
    1936              :         };
    1937              : 
    1938              :         self.timeline_init_and_sync(
    1939              :             timeline_id,
    1940              :             resources,
    1941              :             index_part,
    1942              :             remote_metadata,
    1943              :             previous_heatmap,
    1944              :             ancestor,
    1945              :             cause,
    1946              :             ctx,
    1947              :         )
    1948              :         .await
    1949              :     }
    1950              : 
    1951          117 :     async fn load_timelines_metadata(
    1952          117 :         self: &Arc<TenantShard>,
    1953          117 :         timeline_ids: HashSet<TimelineId>,
    1954          117 :         remote_storage: &GenericRemoteStorage,
    1955          117 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    1956          117 :         cancel: CancellationToken,
    1957          117 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1958          117 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    1959          117 : 
    1960          117 :         let mut part_downloads = JoinSet::new();
    1961          120 :         for timeline_id in timeline_ids {
    1962            3 :             let cancel_clone = cancel.clone();
    1963            3 : 
    1964            3 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    1965            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    1966            0 :                     heatmap: h,
    1967            0 :                     read_at: hs.1,
    1968            0 :                     end_lsn: None,
    1969            0 :                 })
    1970            3 :             });
    1971            3 :             part_downloads.spawn(
    1972            3 :                 self.load_timeline_metadata(
    1973            3 :                     timeline_id,
    1974            3 :                     remote_storage.clone(),
    1975            3 :                     previous_timeline_heatmap,
    1976            3 :                     cancel_clone,
    1977            3 :                 )
    1978            3 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    1979              :             );
    1980              :         }
    1981              : 
    1982          117 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1983              : 
    1984              :         loop {
    1985          120 :             tokio::select!(
    1986          120 :                 next = part_downloads.join_next() => {
    1987          120 :                     match next {
    1988            3 :                         Some(result) => {
    1989            3 :                             let preload = result.context("join preload task")?;
    1990            3 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1991              :                         },
    1992              :                         None => {
    1993          117 :                             break;
    1994              :                         }
    1995              :                     }
    1996              :                 },
    1997          120 :                 _ = cancel.cancelled() => {
    1998            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1999              :                 }
    2000              :             )
    2001              :         }
    2002              : 
    2003          117 :         Ok(timeline_preloads)
    2004          117 :     }
    2005              : 
    2006            3 :     fn build_timeline_client(
    2007            3 :         &self,
    2008            3 :         timeline_id: TimelineId,
    2009            3 :         remote_storage: GenericRemoteStorage,
    2010            3 :     ) -> RemoteTimelineClient {
    2011            3 :         RemoteTimelineClient::new(
    2012            3 :             remote_storage.clone(),
    2013            3 :             self.deletion_queue_client.clone(),
    2014            3 :             self.conf,
    2015            3 :             self.tenant_shard_id,
    2016            3 :             timeline_id,
    2017            3 :             self.generation,
    2018            3 :             &self.tenant_conf.load().location,
    2019            3 :         )
    2020            3 :     }
    2021              : 
    2022            3 :     fn load_timeline_metadata(
    2023            3 :         self: &Arc<TenantShard>,
    2024            3 :         timeline_id: TimelineId,
    2025            3 :         remote_storage: GenericRemoteStorage,
    2026            3 :         previous_heatmap: Option<PreviousHeatmap>,
    2027            3 :         cancel: CancellationToken,
    2028            3 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2029            3 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2030            3 :         async move {
    2031            3 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2032            3 :             debug!("starting index part download");
    2033              : 
    2034            3 :             let index_part = client.download_index_file(&cancel).await;
    2035              : 
    2036            3 :             debug!("finished index part download");
    2037              : 
    2038            3 :             TimelinePreload {
    2039            3 :                 client,
    2040            3 :                 timeline_id,
    2041            3 :                 index_part,
    2042            3 :                 previous_heatmap,
    2043            3 :             }
    2044            3 :         }
    2045            3 :     }
    2046              : 
    2047            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2048            0 :         timeline_id: TimelineId,
    2049            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2050            0 :     ) -> Result<(), TimelineArchivalError> {
    2051            0 :         let children: Vec<TimelineId> = timelines
    2052            0 :             .iter()
    2053            0 :             .filter_map(|(id, entry)| {
    2054            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2055            0 :                     return None;
    2056            0 :                 }
    2057            0 :                 if entry.is_archived() == Some(true) {
    2058            0 :                     return None;
    2059            0 :                 }
    2060            0 :                 Some(*id)
    2061            0 :             })
    2062            0 :             .collect();
    2063            0 : 
    2064            0 :         if !children.is_empty() {
    2065            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2066            0 :         }
    2067            0 :         Ok(())
    2068            0 :     }
    2069              : 
    2070            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2071            0 :         ancestor_timeline_id: TimelineId,
    2072            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2073            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2074            0 :             '_,
    2075            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2076            0 :         >,
    2077            0 :     ) -> Result<(), TimelineArchivalError> {
    2078            0 :         let has_archived_parent =
    2079            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2080            0 :                 ancestor_timeline.is_archived() == Some(true)
    2081            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2082            0 :                 true
    2083              :             } else {
    2084            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2085            0 :                 if cfg!(debug_assertions) {
    2086            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2087            0 :                 }
    2088            0 :                 return Err(TimelineArchivalError::NotFound);
    2089              :             };
    2090            0 :         if has_archived_parent {
    2091            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2092            0 :                 ancestor_timeline_id,
    2093            0 :             ));
    2094            0 :         }
    2095            0 :         Ok(())
    2096            0 :     }
    2097              : 
    2098            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2099            0 :         timeline: &Arc<Timeline>,
    2100            0 :     ) -> Result<(), TimelineArchivalError> {
    2101            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2102            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2103            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2104            0 :                     ancestor_timeline.timeline_id,
    2105            0 :                 ));
    2106            0 :             }
    2107            0 :         }
    2108            0 :         Ok(())
    2109            0 :     }
    2110              : 
    2111              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2112              :     ///
    2113              :     /// Counterpart to [`offload_timeline`].
    2114            0 :     async fn unoffload_timeline(
    2115            0 :         self: &Arc<Self>,
    2116            0 :         timeline_id: TimelineId,
    2117            0 :         broker_client: storage_broker::BrokerClientChannel,
    2118            0 :         ctx: RequestContext,
    2119            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2120            0 :         info!("unoffloading timeline");
    2121              : 
    2122              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2123              :         // We expect callers of this function to ensure this.
    2124            0 :         match self.current_state() {
    2125              :             TenantState::Activating { .. }
    2126              :             | TenantState::Attaching
    2127              :             | TenantState::Broken { .. } => {
    2128            0 :                 panic!("Timeline expected to be active")
    2129              :             }
    2130            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2131            0 :             TenantState::Active => {}
    2132            0 :         }
    2133            0 :         let cancel = self.cancel.clone();
    2134            0 : 
    2135            0 :         // Protect against concurrent attempts to use this TimelineId
    2136            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2137            0 :         let allow_offloaded = true;
    2138            0 :         let _create_guard = self
    2139            0 :             .create_timeline_create_guard(
    2140            0 :                 timeline_id,
    2141            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2142            0 :                 allow_offloaded,
    2143            0 :             )
    2144            0 :             .map_err(|err| match err {
    2145            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2146              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2147            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2148              :                 }
    2149            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2150            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2151            0 :             })?;
    2152              : 
    2153            0 :         let timeline_preload = self
    2154            0 :             .load_timeline_metadata(
    2155            0 :                 timeline_id,
    2156            0 :                 self.remote_storage.clone(),
    2157            0 :                 None,
    2158            0 :                 cancel.clone(),
    2159            0 :             )
    2160            0 :             .await;
    2161              : 
    2162            0 :         let index_part = match timeline_preload.index_part {
    2163            0 :             Ok(index_part) => {
    2164            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2165            0 :                 index_part
    2166              :             }
    2167              :             Err(DownloadError::NotFound) => {
    2168            0 :                 error!(%timeline_id, "index_part not found on remote");
    2169            0 :                 return Err(TimelineArchivalError::NotFound);
    2170              :             }
    2171            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2172            0 :             Err(e) => {
    2173            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2174            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2175            0 :                 return Err(TimelineArchivalError::Other(
    2176            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2177            0 :                 ));
    2178              :             }
    2179              :         };
    2180            0 :         let index_part = match index_part {
    2181            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2182            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2183            0 :                 info!("timeline is deleted according to index_part.json");
    2184            0 :                 return Err(TimelineArchivalError::NotFound);
    2185              :             }
    2186              :         };
    2187            0 :         let remote_metadata = index_part.metadata.clone();
    2188            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2189            0 :         self.load_remote_timeline(
    2190            0 :             timeline_id,
    2191            0 :             index_part,
    2192            0 :             remote_metadata,
    2193            0 :             None,
    2194            0 :             timeline_resources,
    2195            0 :             LoadTimelineCause::Unoffload,
    2196            0 :             &ctx,
    2197            0 :         )
    2198            0 :         .await
    2199            0 :         .with_context(|| {
    2200            0 :             format!(
    2201            0 :                 "failed to load remote timeline {} for tenant {}",
    2202            0 :                 timeline_id, self.tenant_shard_id
    2203            0 :             )
    2204            0 :         })
    2205            0 :         .map_err(TimelineArchivalError::Other)?;
    2206              : 
    2207            0 :         let timeline = {
    2208            0 :             let timelines = self.timelines.lock().unwrap();
    2209            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2210            0 :                 warn!("timeline not available directly after attach");
    2211              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2212              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2213            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2214            0 :                     "timeline not available directly after attach"
    2215            0 :                 )));
    2216              :             };
    2217            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2218            0 :             match offloaded_timelines.remove(&timeline_id) {
    2219            0 :                 Some(offloaded) => {
    2220            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2221            0 :                 }
    2222            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2223              :             }
    2224              : 
    2225            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2226            0 : 
    2227            0 :             Arc::clone(timeline)
    2228            0 :         };
    2229            0 : 
    2230            0 :         // Upload new list of offloaded timelines to S3
    2231            0 :         self.maybe_upload_tenant_manifest().await?;
    2232              : 
    2233              :         // Activate the timeline (if it makes sense)
    2234            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2235            0 :             let background_jobs_can_start = None;
    2236            0 :             timeline.activate(
    2237            0 :                 self.clone(),
    2238            0 :                 broker_client.clone(),
    2239            0 :                 background_jobs_can_start,
    2240            0 :                 &ctx.with_scope_timeline(&timeline),
    2241            0 :             );
    2242            0 :         }
    2243              : 
    2244            0 :         info!("timeline unoffloading complete");
    2245            0 :         Ok(timeline)
    2246            0 :     }
    2247              : 
    2248            0 :     pub(crate) async fn apply_timeline_archival_config(
    2249            0 :         self: &Arc<Self>,
    2250            0 :         timeline_id: TimelineId,
    2251            0 :         new_state: TimelineArchivalState,
    2252            0 :         broker_client: storage_broker::BrokerClientChannel,
    2253            0 :         ctx: RequestContext,
    2254            0 :     ) -> Result<(), TimelineArchivalError> {
    2255            0 :         info!("setting timeline archival config");
    2256              :         // First part: figure out what is needed to do, and do validation
    2257            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2258            0 :             let timelines = self.timelines.lock().unwrap();
    2259              : 
    2260            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2261            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2262            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2263            0 :                     return Err(TimelineArchivalError::NotFound);
    2264              :                 };
    2265            0 :                 if new_state == TimelineArchivalState::Archived {
    2266              :                     // It's offloaded already, so nothing to do
    2267            0 :                     return Ok(());
    2268            0 :                 }
    2269            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2270            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2271            0 :                         ancestor_timeline_id,
    2272            0 :                         &timelines,
    2273            0 :                         &offloaded_timelines,
    2274            0 :                     )?;
    2275            0 :                 }
    2276            0 :                 break 'outer None;
    2277              :             };
    2278              : 
    2279              :             // Do some validation. We release the timelines lock below, so there is potential
    2280              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2281              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2282            0 :             match new_state {
    2283              :                 TimelineArchivalState::Unarchived => {
    2284            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2285              :                 }
    2286              :                 TimelineArchivalState::Archived => {
    2287            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2288              :                 }
    2289              :             }
    2290            0 :             Some(Arc::clone(timeline))
    2291              :         };
    2292              : 
    2293              :         // Second part: unoffload timeline (if needed)
    2294            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2295            0 :             timeline
    2296              :         } else {
    2297              :             // Turn offloaded timeline into a non-offloaded one
    2298            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2299            0 :                 .await?
    2300              :         };
    2301              : 
    2302              :         // Third part: upload new timeline archival state and block until it is present in S3
    2303            0 :         let upload_needed = match timeline
    2304            0 :             .remote_client
    2305            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2306              :         {
    2307            0 :             Ok(upload_needed) => upload_needed,
    2308            0 :             Err(e) => {
    2309            0 :                 if timeline.cancel.is_cancelled() {
    2310            0 :                     return Err(TimelineArchivalError::Cancelled);
    2311              :                 } else {
    2312            0 :                     return Err(TimelineArchivalError::Other(e));
    2313              :                 }
    2314              :             }
    2315              :         };
    2316              : 
    2317            0 :         if upload_needed {
    2318            0 :             info!("Uploading new state");
    2319              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2320            0 :             let Ok(v) =
    2321            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2322              :             else {
    2323            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2324            0 :                 return Err(TimelineArchivalError::Timeout);
    2325              :             };
    2326            0 :             v.map_err(|e| match e {
    2327            0 :                 WaitCompletionError::NotInitialized(e) => {
    2328            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2329              :                 }
    2330              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2331            0 :                     TimelineArchivalError::Cancelled
    2332              :                 }
    2333            0 :             })?;
    2334            0 :         }
    2335            0 :         Ok(())
    2336            0 :     }
    2337              : 
    2338            1 :     pub fn get_offloaded_timeline(
    2339            1 :         &self,
    2340            1 :         timeline_id: TimelineId,
    2341            1 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2342            1 :         self.timelines_offloaded
    2343            1 :             .lock()
    2344            1 :             .unwrap()
    2345            1 :             .get(&timeline_id)
    2346            1 :             .map(Arc::clone)
    2347            1 :             .ok_or(GetTimelineError::NotFound {
    2348            1 :                 tenant_id: self.tenant_shard_id,
    2349            1 :                 timeline_id,
    2350            1 :             })
    2351            1 :     }
    2352              : 
    2353            2 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2354            2 :         self.tenant_shard_id
    2355            2 :     }
    2356              : 
    2357              :     /// Get Timeline handle for given Neon timeline ID.
    2358              :     /// This function is idempotent. It doesn't change internal state in any way.
    2359          111 :     pub fn get_timeline(
    2360          111 :         &self,
    2361          111 :         timeline_id: TimelineId,
    2362          111 :         active_only: bool,
    2363          111 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2364          111 :         let timelines_accessor = self.timelines.lock().unwrap();
    2365          111 :         let timeline = timelines_accessor
    2366          111 :             .get(&timeline_id)
    2367          111 :             .ok_or(GetTimelineError::NotFound {
    2368          111 :                 tenant_id: self.tenant_shard_id,
    2369          111 :                 timeline_id,
    2370          111 :             })?;
    2371              : 
    2372          110 :         if active_only && !timeline.is_active() {
    2373            0 :             Err(GetTimelineError::NotActive {
    2374            0 :                 tenant_id: self.tenant_shard_id,
    2375            0 :                 timeline_id,
    2376            0 :                 state: timeline.current_state(),
    2377            0 :             })
    2378              :         } else {
    2379          110 :             Ok(Arc::clone(timeline))
    2380              :         }
    2381          111 :     }
    2382              : 
    2383              :     /// Lists timelines the tenant contains.
    2384              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2385            2 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2386            2 :         self.timelines
    2387            2 :             .lock()
    2388            2 :             .unwrap()
    2389            2 :             .values()
    2390            2 :             .map(Arc::clone)
    2391            2 :             .collect()
    2392            2 :     }
    2393              : 
    2394              :     /// Lists timelines the tenant manages, including offloaded ones.
    2395              :     ///
    2396              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2397            0 :     pub fn list_timelines_and_offloaded(
    2398            0 :         &self,
    2399            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2400            0 :         let timelines = self
    2401            0 :             .timelines
    2402            0 :             .lock()
    2403            0 :             .unwrap()
    2404            0 :             .values()
    2405            0 :             .map(Arc::clone)
    2406            0 :             .collect();
    2407            0 :         let offloaded = self
    2408            0 :             .timelines_offloaded
    2409            0 :             .lock()
    2410            0 :             .unwrap()
    2411            0 :             .values()
    2412            0 :             .map(Arc::clone)
    2413            0 :             .collect();
    2414            0 :         (timelines, offloaded)
    2415            0 :     }
    2416              : 
    2417            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2418            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2419            0 :     }
    2420              : 
    2421              :     /// This is used by tests & import-from-basebackup.
    2422              :     ///
    2423              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2424              :     /// a state that will fail [`TenantShard::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2425              :     ///
    2426              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2427              :     /// by [`TenantShard::load_remote_timeline`] / [`TenantShard::attach`].
    2428              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2429              :     /// to the [`TenantShard::timelines`].
    2430              :     ///
    2431              :     /// Tests should use `TenantShard::create_test_timeline` to set up the minimum required metadata keys.
    2432          113 :     pub(crate) async fn create_empty_timeline(
    2433          113 :         self: &Arc<Self>,
    2434          113 :         new_timeline_id: TimelineId,
    2435          113 :         initdb_lsn: Lsn,
    2436          113 :         pg_version: u32,
    2437          113 :         ctx: &RequestContext,
    2438          113 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2439          113 :         anyhow::ensure!(
    2440          113 :             self.is_active(),
    2441            0 :             "Cannot create empty timelines on inactive tenant"
    2442              :         );
    2443              : 
    2444              :         // Protect against concurrent attempts to use this TimelineId
    2445          113 :         let create_guard = match self
    2446          113 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2447          113 :             .await?
    2448              :         {
    2449          112 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2450              :             StartCreatingTimelineResult::Idempotent(_) => {
    2451            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2452              :             }
    2453              :         };
    2454              : 
    2455          112 :         let new_metadata = TimelineMetadata::new(
    2456          112 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2457          112 :             // make it valid, before calling finish_creation()
    2458          112 :             Lsn(0),
    2459          112 :             None,
    2460          112 :             None,
    2461          112 :             Lsn(0),
    2462          112 :             initdb_lsn,
    2463          112 :             initdb_lsn,
    2464          112 :             pg_version,
    2465          112 :         );
    2466          112 :         self.prepare_new_timeline(
    2467          112 :             new_timeline_id,
    2468          112 :             &new_metadata,
    2469          112 :             create_guard,
    2470          112 :             initdb_lsn,
    2471          112 :             None,
    2472          112 :             None,
    2473          112 :             ctx,
    2474          112 :         )
    2475          112 :         .await
    2476          113 :     }
    2477              : 
    2478              :     /// Helper for unit tests to create an empty timeline.
    2479              :     ///
    2480              :     /// The timeline is has state value `Active` but its background loops are not running.
    2481              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2482              :     // Our current tests don't need the background loops.
    2483              :     #[cfg(test)]
    2484          108 :     pub async fn create_test_timeline(
    2485          108 :         self: &Arc<Self>,
    2486          108 :         new_timeline_id: TimelineId,
    2487          108 :         initdb_lsn: Lsn,
    2488          108 :         pg_version: u32,
    2489          108 :         ctx: &RequestContext,
    2490          108 :     ) -> anyhow::Result<Arc<Timeline>> {
    2491          108 :         let (uninit_tl, ctx) = self
    2492          108 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2493          108 :             .await?;
    2494          108 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2495          108 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2496              : 
    2497              :         // Setup minimum keys required for the timeline to be usable.
    2498          108 :         let mut modification = tline.begin_modification(initdb_lsn);
    2499          108 :         modification
    2500          108 :             .init_empty_test_timeline()
    2501          108 :             .context("init_empty_test_timeline")?;
    2502          108 :         modification
    2503          108 :             .commit(&ctx)
    2504          108 :             .await
    2505          108 :             .context("commit init_empty_test_timeline modification")?;
    2506              : 
    2507              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2508          108 :         tline.maybe_spawn_flush_loop();
    2509          108 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2510              : 
    2511              :         // Make sure the freeze_and_flush reaches remote storage.
    2512          108 :         tline.remote_client.wait_completion().await.unwrap();
    2513              : 
    2514          108 :         let tl = uninit_tl.finish_creation().await?;
    2515              :         // The non-test code would call tl.activate() here.
    2516          108 :         tl.set_state(TimelineState::Active);
    2517          108 :         Ok(tl)
    2518          108 :     }
    2519              : 
    2520              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2521              :     #[cfg(test)]
    2522              :     #[allow(clippy::too_many_arguments)]
    2523           24 :     pub async fn create_test_timeline_with_layers(
    2524           24 :         self: &Arc<Self>,
    2525           24 :         new_timeline_id: TimelineId,
    2526           24 :         initdb_lsn: Lsn,
    2527           24 :         pg_version: u32,
    2528           24 :         ctx: &RequestContext,
    2529           24 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2530           24 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2531           24 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2532           24 :         end_lsn: Lsn,
    2533           24 :     ) -> anyhow::Result<Arc<Timeline>> {
    2534              :         use checks::check_valid_layermap;
    2535              :         use itertools::Itertools;
    2536              : 
    2537           24 :         let tline = self
    2538           24 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2539           24 :             .await?;
    2540           24 :         tline.force_advance_lsn(end_lsn);
    2541           71 :         for deltas in delta_layer_desc {
    2542           47 :             tline
    2543           47 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2544           47 :                 .await?;
    2545              :         }
    2546           58 :         for (lsn, images) in image_layer_desc {
    2547           34 :             tline
    2548           34 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2549           34 :                 .await?;
    2550              :         }
    2551           28 :         for in_memory in in_memory_layer_desc {
    2552            4 :             tline
    2553            4 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2554            4 :                 .await?;
    2555              :         }
    2556           24 :         let layer_names = tline
    2557           24 :             .layers
    2558           24 :             .read()
    2559           24 :             .await
    2560           24 :             .layer_map()
    2561           24 :             .unwrap()
    2562           24 :             .iter_historic_layers()
    2563          105 :             .map(|layer| layer.layer_name())
    2564           24 :             .collect_vec();
    2565           24 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2566            0 :             bail!("invalid layermap: {err}");
    2567           24 :         }
    2568           24 :         Ok(tline)
    2569           24 :     }
    2570              : 
    2571              :     /// Create a new timeline.
    2572              :     ///
    2573              :     /// Returns the new timeline ID and reference to its Timeline object.
    2574              :     ///
    2575              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2576              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2577              :     #[allow(clippy::too_many_arguments)]
    2578            0 :     pub(crate) async fn create_timeline(
    2579            0 :         self: &Arc<TenantShard>,
    2580            0 :         params: CreateTimelineParams,
    2581            0 :         broker_client: storage_broker::BrokerClientChannel,
    2582            0 :         ctx: &RequestContext,
    2583            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2584            0 :         if !self.is_active() {
    2585            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2586            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2587              :             } else {
    2588            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2589            0 :                     "Cannot create timelines on inactive tenant"
    2590            0 :                 )));
    2591              :             }
    2592            0 :         }
    2593              : 
    2594            0 :         let _gate = self
    2595            0 :             .gate
    2596            0 :             .enter()
    2597            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2598              : 
    2599            0 :         let result: CreateTimelineResult = match params {
    2600              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2601            0 :                 new_timeline_id,
    2602            0 :                 existing_initdb_timeline_id,
    2603            0 :                 pg_version,
    2604            0 :             }) => {
    2605            0 :                 self.bootstrap_timeline(
    2606            0 :                     new_timeline_id,
    2607            0 :                     pg_version,
    2608            0 :                     existing_initdb_timeline_id,
    2609            0 :                     ctx,
    2610            0 :                 )
    2611            0 :                 .await?
    2612              :             }
    2613              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2614            0 :                 new_timeline_id,
    2615            0 :                 ancestor_timeline_id,
    2616            0 :                 mut ancestor_start_lsn,
    2617              :             }) => {
    2618            0 :                 let ancestor_timeline = self
    2619            0 :                     .get_timeline(ancestor_timeline_id, false)
    2620            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2621              : 
    2622              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2623              :                 // ready for other purposes either.
    2624            0 :                 if !ancestor_timeline.is_active() {
    2625            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2626            0 :                 }
    2627            0 : 
    2628            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2629            0 :                     info!("tried to branch archived timeline");
    2630            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2631            0 :                 }
    2632              : 
    2633            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2634            0 :                     *lsn = lsn.align();
    2635            0 : 
    2636            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2637            0 :                     if ancestor_ancestor_lsn > *lsn {
    2638              :                         // can we safely just branch from the ancestor instead?
    2639            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2640            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2641            0 :                             lsn,
    2642            0 :                             ancestor_timeline_id,
    2643            0 :                             ancestor_ancestor_lsn,
    2644            0 :                         )));
    2645            0 :                     }
    2646            0 : 
    2647            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2648            0 :                     // to the requested branch point. The repository code itself doesn't
    2649            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2650            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2651            0 :                     // sizes etc. and that would get confused if the previous page versions
    2652            0 :                     // are not in the repository yet.
    2653            0 :                     ancestor_timeline
    2654            0 :                         .wait_lsn(
    2655            0 :                             *lsn,
    2656            0 :                             timeline::WaitLsnWaiter::Tenant,
    2657            0 :                             timeline::WaitLsnTimeout::Default,
    2658            0 :                             ctx,
    2659            0 :                         )
    2660            0 :                         .await
    2661            0 :                         .map_err(|e| match e {
    2662            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2663            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2664              :                             }
    2665            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2666            0 :                         })?;
    2667            0 :                 }
    2668              : 
    2669            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2670            0 :                     .await?
    2671              :             }
    2672            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2673            0 :                 self.create_timeline_import_pgdata(params, ctx).await?
    2674              :             }
    2675              :         };
    2676              : 
    2677              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2678              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2679              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2680              :         //
    2681              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2682              :         // assume that, because they can see the timeline via API, that the creation is done and
    2683              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2684              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2685              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2686              :         //
    2687              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2688              :         // creation API until it returns success. Only then is durability guaranteed.
    2689            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2690            0 :         result
    2691            0 :             .timeline()
    2692            0 :             .remote_client
    2693            0 :             .wait_completion()
    2694            0 :             .await
    2695            0 :             .map_err(|e| match e {
    2696              :                 WaitCompletionError::NotInitialized(
    2697            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2698            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2699              :                 WaitCompletionError::NotInitialized(_) => {
    2700              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2701            0 :                     debug_assert!(false);
    2702            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2703              :                 }
    2704              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2705            0 :                     CreateTimelineError::ShuttingDown
    2706              :                 }
    2707            0 :             })?;
    2708              : 
    2709              :         // The creating task is responsible for activating the timeline.
    2710              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2711              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2712            0 :         let activated_timeline = match result {
    2713            0 :             CreateTimelineResult::Created(timeline) => {
    2714            0 :                 timeline.activate(
    2715            0 :                     self.clone(),
    2716            0 :                     broker_client,
    2717            0 :                     None,
    2718            0 :                     &ctx.with_scope_timeline(&timeline),
    2719            0 :                 );
    2720            0 :                 timeline
    2721              :             }
    2722            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2723            0 :                 info!(
    2724            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2725              :                 );
    2726            0 :                 timeline
    2727              :             }
    2728            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2729            0 :                 info!(
    2730            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2731              :                 );
    2732            0 :                 timeline
    2733              :             }
    2734              :         };
    2735              : 
    2736            0 :         Ok(activated_timeline)
    2737            0 :     }
    2738              : 
    2739              :     /// The returned [`Arc<Timeline>`] is NOT in the [`TenantShard::timelines`] map until the import
    2740              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2741              :     /// [`TenantShard::timelines`] map when the import completes.
    2742              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2743              :     /// for the response.
    2744            0 :     async fn create_timeline_import_pgdata(
    2745            0 :         self: &Arc<Self>,
    2746            0 :         params: CreateTimelineParamsImportPgdata,
    2747            0 :         ctx: &RequestContext,
    2748            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2749            0 :         let CreateTimelineParamsImportPgdata {
    2750            0 :             new_timeline_id,
    2751            0 :             location,
    2752            0 :             idempotency_key,
    2753            0 :         } = params;
    2754            0 : 
    2755            0 :         let started_at = chrono::Utc::now().naive_utc();
    2756              : 
    2757              :         //
    2758              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2759              :         // is the canonical way we do it.
    2760              :         // - create an empty timeline in-memory
    2761              :         // - use its remote_timeline_client to do the upload
    2762              :         // - dispose of the uninit timeline
    2763              :         // - keep the creation guard alive
    2764              : 
    2765            0 :         let timeline_create_guard = match self
    2766            0 :             .start_creating_timeline(
    2767            0 :                 new_timeline_id,
    2768            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2769            0 :                     idempotency_key: idempotency_key.clone(),
    2770            0 :                 }),
    2771            0 :             )
    2772            0 :             .await?
    2773              :         {
    2774            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2775            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2776            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2777              :             }
    2778              :         };
    2779              : 
    2780            0 :         let (mut uninit_timeline, timeline_ctx) = {
    2781            0 :             let this = &self;
    2782            0 :             let initdb_lsn = Lsn(0);
    2783            0 :             async move {
    2784            0 :                 let new_metadata = TimelineMetadata::new(
    2785            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2786            0 :                     // make it valid, before calling finish_creation()
    2787            0 :                     Lsn(0),
    2788            0 :                     None,
    2789            0 :                     None,
    2790            0 :                     Lsn(0),
    2791            0 :                     initdb_lsn,
    2792            0 :                     initdb_lsn,
    2793            0 :                     15,
    2794            0 :                 );
    2795            0 :                 this.prepare_new_timeline(
    2796            0 :                     new_timeline_id,
    2797            0 :                     &new_metadata,
    2798            0 :                     timeline_create_guard,
    2799            0 :                     initdb_lsn,
    2800            0 :                     None,
    2801            0 :                     None,
    2802            0 :                     ctx,
    2803            0 :                 )
    2804            0 :                 .await
    2805            0 :             }
    2806            0 :         }
    2807            0 :         .await?;
    2808              : 
    2809            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2810            0 :             idempotency_key,
    2811            0 :             location,
    2812            0 :             started_at,
    2813            0 :         };
    2814            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2815            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2816            0 :         );
    2817            0 :         uninit_timeline
    2818            0 :             .raw_timeline()
    2819            0 :             .unwrap()
    2820            0 :             .remote_client
    2821            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2822              : 
    2823              :         // wait_completion happens in caller
    2824              : 
    2825            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2826            0 : 
    2827            0 :         let import_task_handle = tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2828            0 :             timeline.clone(),
    2829            0 :             index_part,
    2830            0 :             timeline_create_guard,
    2831            0 :             timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    2832            0 :         ));
    2833            0 : 
    2834            0 :         let prev = self.timelines_importing.lock().unwrap().insert(
    2835            0 :             timeline.timeline_id,
    2836            0 :             ImportingTimeline {
    2837            0 :                 timeline: timeline.clone(),
    2838            0 :                 import_task_handle,
    2839            0 :             },
    2840            0 :         );
    2841            0 : 
    2842            0 :         // Idempotency is enforced higher up the stack
    2843            0 :         assert!(prev.is_none());
    2844              : 
    2845              :         // NB: the timeline doesn't exist in self.timelines at this point
    2846            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2847            0 :     }
    2848              : 
    2849              :     /// Finalize the import of a timeline on this shard by marking it complete in
    2850              :     /// the index part. If the import task hasn't finished yet, returns an error.
    2851              :     ///
    2852              :     /// This method is idempotent. If the import was finalized once, the next call
    2853              :     /// will be a no-op.
    2854            0 :     pub(crate) async fn finalize_importing_timeline(
    2855            0 :         &self,
    2856            0 :         timeline_id: TimelineId,
    2857            0 :     ) -> anyhow::Result<()> {
    2858            0 :         let timeline = {
    2859            0 :             let locked = self.timelines_importing.lock().unwrap();
    2860            0 :             match locked.get(&timeline_id) {
    2861            0 :                 Some(importing_timeline) => {
    2862            0 :                     if !importing_timeline.import_task_handle.is_finished() {
    2863            0 :                         return Err(anyhow::anyhow!("Import task not done yet"));
    2864            0 :                     }
    2865            0 : 
    2866            0 :                     importing_timeline.timeline.clone()
    2867              :                 }
    2868              :                 None => {
    2869            0 :                     return Ok(());
    2870              :                 }
    2871              :             }
    2872              :         };
    2873              : 
    2874            0 :         timeline
    2875            0 :             .remote_client
    2876            0 :             .schedule_index_upload_for_import_pgdata_finalize()?;
    2877            0 :         timeline.remote_client.wait_completion().await?;
    2878              : 
    2879            0 :         self.timelines_importing
    2880            0 :             .lock()
    2881            0 :             .unwrap()
    2882            0 :             .remove(&timeline_id);
    2883            0 : 
    2884            0 :         Ok(())
    2885            0 :     }
    2886              : 
    2887              :     #[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))]
    2888              :     async fn create_timeline_import_pgdata_task(
    2889              :         self: Arc<TenantShard>,
    2890              :         timeline: Arc<Timeline>,
    2891              :         index_part: import_pgdata::index_part_format::Root,
    2892              :         timeline_create_guard: TimelineCreateGuard,
    2893              :         ctx: RequestContext,
    2894              :     ) {
    2895              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2896              :         info!("starting");
    2897              :         scopeguard::defer! {info!("exiting")};
    2898              : 
    2899              :         let res = self
    2900              :             .create_timeline_import_pgdata_task_impl(
    2901              :                 timeline,
    2902              :                 index_part,
    2903              :                 timeline_create_guard,
    2904              :                 ctx,
    2905              :             )
    2906              :             .await;
    2907              :         if let Err(err) = &res {
    2908              :             error!(?err, "task failed");
    2909              :             // TODO sleep & retry, sensitive to tenant shutdown
    2910              :             // TODO: allow timeline deletion requests => should cancel the task
    2911              :         }
    2912              :     }
    2913              : 
    2914            0 :     async fn create_timeline_import_pgdata_task_impl(
    2915            0 :         self: Arc<TenantShard>,
    2916            0 :         timeline: Arc<Timeline>,
    2917            0 :         index_part: import_pgdata::index_part_format::Root,
    2918            0 :         _timeline_create_guard: TimelineCreateGuard,
    2919            0 :         ctx: RequestContext,
    2920            0 :     ) -> Result<(), anyhow::Error> {
    2921            0 :         info!("importing pgdata");
    2922            0 :         let ctx = ctx.with_scope_timeline(&timeline);
    2923            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2924            0 :             .await
    2925            0 :             .context("import")?;
    2926            0 :         info!("import done - waiting for activation");
    2927              : 
    2928            0 :         anyhow::Ok(())
    2929            0 :     }
    2930              : 
    2931            0 :     pub(crate) async fn delete_timeline(
    2932            0 :         self: Arc<Self>,
    2933            0 :         timeline_id: TimelineId,
    2934            0 :     ) -> Result<(), DeleteTimelineError> {
    2935            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2936              : 
    2937            0 :         Ok(())
    2938            0 :     }
    2939              : 
    2940              :     /// perform one garbage collection iteration, removing old data files from disk.
    2941              :     /// this function is periodically called by gc task.
    2942              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2943              :     ///
    2944              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2945              :     ///
    2946              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2947              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2948              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2949              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2950              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2951              :     /// requires more history to be retained.
    2952              :     //
    2953          377 :     pub(crate) async fn gc_iteration(
    2954          377 :         &self,
    2955          377 :         target_timeline_id: Option<TimelineId>,
    2956          377 :         horizon: u64,
    2957          377 :         pitr: Duration,
    2958          377 :         cancel: &CancellationToken,
    2959          377 :         ctx: &RequestContext,
    2960          377 :     ) -> Result<GcResult, GcError> {
    2961          377 :         // Don't start doing work during shutdown
    2962          377 :         if let TenantState::Stopping { .. } = self.current_state() {
    2963            0 :             return Ok(GcResult::default());
    2964          377 :         }
    2965          377 : 
    2966          377 :         // there is a global allowed_error for this
    2967          377 :         if !self.is_active() {
    2968            0 :             return Err(GcError::NotActive);
    2969          377 :         }
    2970          377 : 
    2971          377 :         {
    2972          377 :             let conf = self.tenant_conf.load();
    2973          377 : 
    2974          377 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2975          377 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2976          377 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2977          377 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2978          377 :             if !conf.location.may_delete_layers_hint() {
    2979            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2980            0 :                 return Ok(GcResult::default());
    2981          377 :             }
    2982          377 : 
    2983          377 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2984          375 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2985          375 :                 return Ok(GcResult::default());
    2986            2 :             }
    2987              :         }
    2988              : 
    2989            2 :         let _guard = match self.gc_block.start().await {
    2990            2 :             Ok(guard) => guard,
    2991            0 :             Err(reasons) => {
    2992            0 :                 info!("Skipping GC: {reasons}");
    2993            0 :                 return Ok(GcResult::default());
    2994              :             }
    2995              :         };
    2996              : 
    2997            2 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2998            2 :             .await
    2999          377 :     }
    3000              : 
    3001              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    3002              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    3003              :     /// immediate L0 compaction.
    3004              :     ///
    3005              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    3006            0 :     async fn compaction_iteration(
    3007            0 :         self: &Arc<Self>,
    3008            0 :         cancel: &CancellationToken,
    3009            0 :         ctx: &RequestContext,
    3010            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    3011            0 :         // Don't compact inactive tenants.
    3012            0 :         if !self.is_active() {
    3013            0 :             return Ok(CompactionOutcome::Skipped);
    3014            0 :         }
    3015            0 : 
    3016            0 :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    3017            0 :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    3018            0 :         let location = self.tenant_conf.load().location;
    3019            0 :         if !location.may_upload_layers_hint() {
    3020            0 :             info!("skipping compaction in location state {location:?}");
    3021            0 :             return Ok(CompactionOutcome::Skipped);
    3022            0 :         }
    3023            0 : 
    3024            0 :         // Don't compact if the circuit breaker is tripped.
    3025            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3026            0 :             info!("skipping compaction due to previous failures");
    3027            0 :             return Ok(CompactionOutcome::Skipped);
    3028            0 :         }
    3029            0 : 
    3030            0 :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3031            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3032            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3033            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3034            0 : 
    3035            0 :         {
    3036            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3037            0 :             let timelines = self.timelines.lock().unwrap();
    3038            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3039              :                 // Skip inactive timelines.
    3040            0 :                 if !timeline.is_active() {
    3041            0 :                     continue;
    3042            0 :                 }
    3043            0 : 
    3044            0 :                 // Schedule the timeline for compaction.
    3045            0 :                 compact.push(timeline.clone());
    3046              : 
    3047              :                 // Schedule the timeline for offloading if eligible.
    3048            0 :                 let can_offload = offload_enabled
    3049            0 :                     && timeline.can_offload().0
    3050            0 :                     && !timelines
    3051            0 :                         .iter()
    3052            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3053            0 :                 if can_offload {
    3054            0 :                     offload.insert(timeline_id);
    3055            0 :                 }
    3056              :             }
    3057              :         } // release timelines lock
    3058              : 
    3059            0 :         for timeline in &compact {
    3060              :             // Collect L0 counts. Can't await while holding lock above.
    3061            0 :             if let Ok(lm) = timeline.layers.read().await.layer_map() {
    3062            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3063            0 :             }
    3064              :         }
    3065              : 
    3066              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3067              :         // bound read amplification.
    3068              :         //
    3069              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3070              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3071              :         // splitting L0 and image/GC compaction to separate background jobs.
    3072            0 :         if self.get_compaction_l0_first() {
    3073            0 :             let compaction_threshold = self.get_compaction_threshold();
    3074            0 :             let compact_l0 = compact
    3075            0 :                 .iter()
    3076            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3077            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3078            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3079            0 :                 .rev()
    3080            0 :                 .map(|(tli, _)| tli.clone())
    3081            0 :                 .collect_vec();
    3082            0 : 
    3083            0 :             let mut has_pending_l0 = false;
    3084            0 :             for timeline in compact_l0 {
    3085            0 :                 let ctx = &ctx.with_scope_timeline(&timeline);
    3086              :                 // NB: don't set CompactFlags::YieldForL0, since this is an L0-only compaction pass.
    3087            0 :                 let outcome = timeline
    3088            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3089            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3090            0 :                     .await
    3091            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3092            0 :                 match outcome {
    3093            0 :                     CompactionOutcome::Done => {}
    3094            0 :                     CompactionOutcome::Skipped => {}
    3095            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3096            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3097              :                 }
    3098              :             }
    3099            0 :             if has_pending_l0 {
    3100            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3101            0 :             }
    3102            0 :         }
    3103              : 
    3104              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated more
    3105              :         // L0 layers, they may also be compacted here. Image compaction will yield if there is
    3106              :         // pending L0 compaction on any tenant timeline.
    3107              :         //
    3108              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3109              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3110            0 :         let mut has_pending = false;
    3111            0 :         for timeline in compact {
    3112            0 :             if !timeline.is_active() {
    3113            0 :                 continue;
    3114            0 :             }
    3115            0 :             let ctx = &ctx.with_scope_timeline(&timeline);
    3116            0 : 
    3117            0 :             // Yield for L0 if the separate L0 pass is enabled (otherwise there's no point).
    3118            0 :             let mut flags = EnumSet::default();
    3119            0 :             if self.get_compaction_l0_first() {
    3120            0 :                 flags |= CompactFlags::YieldForL0;
    3121            0 :             }
    3122              : 
    3123            0 :             let mut outcome = timeline
    3124            0 :                 .compact(cancel, flags, ctx)
    3125            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3126            0 :                 .await
    3127            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3128              : 
    3129              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3130            0 :             if outcome == CompactionOutcome::Done {
    3131            0 :                 let queue = {
    3132            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3133            0 :                     guard
    3134            0 :                         .entry(timeline.timeline_id)
    3135            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3136            0 :                         .clone()
    3137            0 :                 };
    3138            0 :                 outcome = queue
    3139            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3140            0 :                     .instrument(
    3141            0 :                         info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
    3142              :                     )
    3143            0 :                     .await?;
    3144            0 :             }
    3145              : 
    3146              :             // If we're done compacting, offload the timeline if requested.
    3147            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3148            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3149            0 :                 offload_timeline(self, &timeline)
    3150            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3151            0 :                     .await
    3152            0 :                     .or_else(|err| match err {
    3153              :                         // Ignore this, we likely raced with unarchival.
    3154            0 :                         OffloadError::NotArchived => Ok(()),
    3155            0 :                         err => Err(err),
    3156            0 :                     })?;
    3157            0 :             }
    3158              : 
    3159            0 :             match outcome {
    3160            0 :                 CompactionOutcome::Done => {}
    3161            0 :                 CompactionOutcome::Skipped => {}
    3162            0 :                 CompactionOutcome::Pending => has_pending = true,
    3163              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3164              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3165            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3166              :             }
    3167              :         }
    3168              : 
    3169              :         // Success! Untrip the breaker if necessary.
    3170            0 :         self.compaction_circuit_breaker
    3171            0 :             .lock()
    3172            0 :             .unwrap()
    3173            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3174            0 : 
    3175            0 :         match has_pending {
    3176            0 :             true => Ok(CompactionOutcome::Pending),
    3177            0 :             false => Ok(CompactionOutcome::Done),
    3178              :         }
    3179            0 :     }
    3180              : 
    3181              :     /// Trips the compaction circuit breaker if appropriate.
    3182            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3183            0 :         match err {
    3184            0 :             err if err.is_cancel() => {}
    3185            0 :             CompactionError::ShuttingDown => (),
    3186              :             // Offload failures don't trip the circuit breaker, since they're cheap to retry and
    3187              :             // shouldn't block compaction.
    3188            0 :             CompactionError::Offload(_) => {}
    3189            0 :             CompactionError::CollectKeySpaceError(err) => {
    3190            0 :                 // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
    3191            0 :                 self.compaction_circuit_breaker
    3192            0 :                     .lock()
    3193            0 :                     .unwrap()
    3194            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3195            0 :             }
    3196            0 :             CompactionError::Other(err) => {
    3197            0 :                 self.compaction_circuit_breaker
    3198            0 :                     .lock()
    3199            0 :                     .unwrap()
    3200            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3201            0 :             }
    3202            0 :             CompactionError::AlreadyRunning(_) => {}
    3203              :         }
    3204            0 :     }
    3205              : 
    3206              :     /// Cancel scheduled compaction tasks
    3207            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3208            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3209            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3210            0 :             q.cancel_scheduled();
    3211            0 :         }
    3212            0 :     }
    3213              : 
    3214            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3215            0 :         &self,
    3216            0 :         timeline_id: TimelineId,
    3217            0 :     ) -> Vec<CompactInfoResponse> {
    3218            0 :         let res = {
    3219            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3220            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3221              :         };
    3222            0 :         let Some((running, remaining)) = res else {
    3223            0 :             return Vec::new();
    3224              :         };
    3225            0 :         let mut result = Vec::new();
    3226            0 :         if let Some((id, running)) = running {
    3227            0 :             result.extend(running.into_compact_info_resp(id, true));
    3228            0 :         }
    3229            0 :         for (id, job) in remaining {
    3230            0 :             result.extend(job.into_compact_info_resp(id, false));
    3231            0 :         }
    3232            0 :         result
    3233            0 :     }
    3234              : 
    3235              :     /// Schedule a compaction task for a timeline.
    3236            0 :     pub(crate) async fn schedule_compaction(
    3237            0 :         &self,
    3238            0 :         timeline_id: TimelineId,
    3239            0 :         options: CompactOptions,
    3240            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3241            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3242            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3243            0 :         let q = guard
    3244            0 :             .entry(timeline_id)
    3245            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3246            0 :         q.schedule_manual_compaction(options, Some(tx));
    3247            0 :         Ok(rx)
    3248            0 :     }
    3249              : 
    3250              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3251            0 :     async fn housekeeping(&self) {
    3252            0 :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3253            0 :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3254            0 :         //
    3255            0 :         // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
    3256            0 :         // We don't run compaction in this case either, and don't want to keep flushing tiny L0
    3257            0 :         // layers that won't be compacted down.
    3258            0 :         if self.tenant_conf.load().location.may_upload_layers_hint() {
    3259            0 :             let timelines = self
    3260            0 :                 .timelines
    3261            0 :                 .lock()
    3262            0 :                 .unwrap()
    3263            0 :                 .values()
    3264            0 :                 .filter(|tli| tli.is_active())
    3265            0 :                 .cloned()
    3266            0 :                 .collect_vec();
    3267              : 
    3268            0 :             for timeline in timelines {
    3269            0 :                 timeline.maybe_freeze_ephemeral_layer().await;
    3270              :             }
    3271            0 :         }
    3272              : 
    3273              :         // Shut down walredo if idle.
    3274              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3275            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3276            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3277            0 :         }
    3278            0 :     }
    3279              : 
    3280            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3281            0 :         let timelines = self.timelines.lock().unwrap();
    3282            0 :         !timelines
    3283            0 :             .iter()
    3284            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3285            0 :     }
    3286              : 
    3287          875 :     pub fn current_state(&self) -> TenantState {
    3288          875 :         self.state.borrow().clone()
    3289          875 :     }
    3290              : 
    3291          494 :     pub fn is_active(&self) -> bool {
    3292          494 :         self.current_state() == TenantState::Active
    3293          494 :     }
    3294              : 
    3295            0 :     pub fn generation(&self) -> Generation {
    3296            0 :         self.generation
    3297            0 :     }
    3298              : 
    3299            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3300            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3301            0 :     }
    3302              : 
    3303              :     /// Changes tenant status to active, unless shutdown was already requested.
    3304              :     ///
    3305              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3306              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3307            0 :     fn activate(
    3308            0 :         self: &Arc<Self>,
    3309            0 :         broker_client: BrokerClientChannel,
    3310            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3311            0 :         ctx: &RequestContext,
    3312            0 :     ) {
    3313            0 :         span::debug_assert_current_span_has_tenant_id();
    3314            0 : 
    3315            0 :         let mut activating = false;
    3316            0 :         self.state.send_modify(|current_state| {
    3317              :             use pageserver_api::models::ActivatingFrom;
    3318            0 :             match &*current_state {
    3319              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3320            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3321              :                 }
    3322            0 :                 TenantState::Attaching => {
    3323            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3324            0 :                 }
    3325            0 :             }
    3326            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3327            0 :             activating = true;
    3328            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3329            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3330            0 :         });
    3331            0 : 
    3332            0 :         if activating {
    3333            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3334            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3335            0 :             let timelines_to_activate = timelines_accessor
    3336            0 :                 .values()
    3337            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3338            0 : 
    3339            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3340            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3341            0 : 
    3342            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3343            0 :             // down when they notice that the tenant is inactive.
    3344            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3345            0 : 
    3346            0 :             let mut activated_timelines = 0;
    3347              : 
    3348            0 :             for timeline in timelines_to_activate {
    3349            0 :                 timeline.activate(
    3350            0 :                     self.clone(),
    3351            0 :                     broker_client.clone(),
    3352            0 :                     background_jobs_can_start,
    3353            0 :                     &ctx.with_scope_timeline(timeline),
    3354            0 :                 );
    3355            0 :                 activated_timelines += 1;
    3356            0 :             }
    3357              : 
    3358            0 :             let tid = self.tenant_shard_id.tenant_id.to_string();
    3359            0 :             let shard_id = self.tenant_shard_id.shard_slug().to_string();
    3360            0 :             let offloaded_timeline_count = timelines_offloaded_accessor.len();
    3361            0 :             TENANT_OFFLOADED_TIMELINES
    3362            0 :                 .with_label_values(&[&tid, &shard_id])
    3363            0 :                 .set(offloaded_timeline_count as u64);
    3364            0 : 
    3365            0 :             self.state.send_modify(move |current_state| {
    3366            0 :                 assert!(
    3367            0 :                     matches!(current_state, TenantState::Activating(_)),
    3368            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3369              :                 );
    3370            0 :                 *current_state = TenantState::Active;
    3371            0 : 
    3372            0 :                 let elapsed = self.constructed_at.elapsed();
    3373            0 :                 let total_timelines = timelines_accessor.len();
    3374            0 : 
    3375            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3376            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3377            0 :                 info!(
    3378            0 :                     since_creation_millis = elapsed.as_millis(),
    3379            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3380            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3381            0 :                     activated_timelines,
    3382            0 :                     total_timelines,
    3383            0 :                     post_state = <&'static str>::from(&*current_state),
    3384            0 :                     "activation attempt finished"
    3385              :                 );
    3386              : 
    3387            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3388            0 :             });
    3389            0 :         }
    3390            0 :     }
    3391              : 
    3392              :     /// Shutdown the tenant and join all of the spawned tasks.
    3393              :     ///
    3394              :     /// The method caters for all use-cases:
    3395              :     /// - pageserver shutdown (freeze_and_flush == true)
    3396              :     /// - detach + ignore (freeze_and_flush == false)
    3397              :     ///
    3398              :     /// This will attempt to shutdown even if tenant is broken.
    3399              :     ///
    3400              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3401              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3402              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3403              :     /// the ongoing shutdown.
    3404            3 :     async fn shutdown(
    3405            3 :         &self,
    3406            3 :         shutdown_progress: completion::Barrier,
    3407            3 :         shutdown_mode: timeline::ShutdownMode,
    3408            3 :     ) -> Result<(), completion::Barrier> {
    3409            3 :         span::debug_assert_current_span_has_tenant_id();
    3410              : 
    3411              :         // Set tenant (and its timlines) to Stoppping state.
    3412              :         //
    3413              :         // Since we can only transition into Stopping state after activation is complete,
    3414              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3415              :         //
    3416              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3417              :         // 1. Lock out any new requests to the tenants.
    3418              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3419              :         // 3. Signal cancellation for other tenant background loops.
    3420              :         // 4. ???
    3421              :         //
    3422              :         // The waiting for the cancellation is not done uniformly.
    3423              :         // We certainly wait for WAL receivers to shut down.
    3424              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3425              :         // But the tenant background loops are joined-on in our caller.
    3426              :         // It's mesed up.
    3427              :         // we just ignore the failure to stop
    3428              : 
    3429              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3430              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3431              :         // is very slow.
    3432            3 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3433            0 :             self.cancel.cancel();
    3434            0 : 
    3435            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3436            0 :             // are children of ours, so their flush loops will have shut down already
    3437            0 :             timeline::ShutdownMode::Hard
    3438              :         } else {
    3439            3 :             shutdown_mode
    3440              :         };
    3441              : 
    3442            3 :         match self.set_stopping(shutdown_progress).await {
    3443            3 :             Ok(()) => {}
    3444            0 :             Err(SetStoppingError::Broken) => {
    3445            0 :                 // assume that this is acceptable
    3446            0 :             }
    3447            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3448            0 :                 // give caller the option to wait for this this shutdown
    3449            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3450            0 :                 return Err(other);
    3451              :             }
    3452              :         };
    3453              : 
    3454            3 :         let mut js = tokio::task::JoinSet::new();
    3455            3 :         {
    3456            3 :             let timelines = self.timelines.lock().unwrap();
    3457            3 :             timelines.values().for_each(|timeline| {
    3458            3 :                 let timeline = Arc::clone(timeline);
    3459            3 :                 let timeline_id = timeline.timeline_id;
    3460            3 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3461            3 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3462            3 :             });
    3463            3 :         }
    3464            3 :         {
    3465            3 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3466            3 :             timelines_offloaded.values().for_each(|timeline| {
    3467            0 :                 timeline.defuse_for_tenant_drop();
    3468            3 :             });
    3469            3 :         }
    3470            3 :         {
    3471            3 :             let mut timelines_importing = self.timelines_importing.lock().unwrap();
    3472            3 :             timelines_importing
    3473            3 :                 .drain()
    3474            3 :                 .for_each(|(_timeline_id, importing_timeline)| {
    3475            0 :                     importing_timeline.shutdown();
    3476            3 :                 });
    3477            3 :         }
    3478            3 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3479            3 :         tracing::info!("Waiting for timelines...");
    3480            6 :         while let Some(res) = js.join_next().await {
    3481            0 :             match res {
    3482            3 :                 Ok(()) => {}
    3483            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3484            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3485            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3486              :             }
    3487              :         }
    3488              : 
    3489            3 :         if let ShutdownMode::Reload = shutdown_mode {
    3490            0 :             tracing::info!("Flushing deletion queue");
    3491            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3492            0 :                 match e {
    3493            0 :                     DeletionQueueError::ShuttingDown => {
    3494            0 :                         // This is the only error we expect for now. In the future, if more error
    3495            0 :                         // variants are added, we should handle them here.
    3496            0 :                     }
    3497              :                 }
    3498            0 :             }
    3499            3 :         }
    3500              : 
    3501              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3502              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3503            3 :         tracing::debug!("Cancelling CancellationToken");
    3504            3 :         self.cancel.cancel();
    3505            3 : 
    3506            3 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3507            3 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3508            3 :         //
    3509            3 :         // this will additionally shutdown and await all timeline tasks.
    3510            3 :         tracing::debug!("Waiting for tasks...");
    3511            3 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3512              : 
    3513            3 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3514            3 :             walredo_mgr.shutdown().await;
    3515            0 :         }
    3516              : 
    3517              :         // Wait for any in-flight operations to complete
    3518            3 :         self.gate.close().await;
    3519              : 
    3520            3 :         remove_tenant_metrics(&self.tenant_shard_id);
    3521            3 : 
    3522            3 :         Ok(())
    3523            3 :     }
    3524              : 
    3525              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3526              :     ///
    3527              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3528              :     ///
    3529              :     /// This function is not cancel-safe!
    3530            3 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3531            3 :         let mut rx = self.state.subscribe();
    3532            3 : 
    3533            3 :         // cannot stop before we're done activating, so wait out until we're done activating
    3534            3 :         rx.wait_for(|state| match state {
    3535              :             TenantState::Activating(_) | TenantState::Attaching => {
    3536            0 :                 info!("waiting for {state} to turn Active|Broken|Stopping");
    3537            0 :                 false
    3538              :             }
    3539            3 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3540            3 :         })
    3541            3 :         .await
    3542            3 :         .expect("cannot drop self.state while on a &self method");
    3543            3 : 
    3544            3 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3545            3 :         let mut err = None;
    3546            3 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3547              :             TenantState::Activating(_) | TenantState::Attaching => {
    3548            0 :                 unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3549              :             }
    3550              :             TenantState::Active => {
    3551              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3552              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3553              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3554            3 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3555            3 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3556            3 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3557            3 :                 true
    3558              :             }
    3559              :             TenantState::Stopping { progress: None } => {
    3560              :                 // An attach was cancelled, and the attach transitioned the tenant from Attaching to
    3561              :                 // Stopping(None) to let us know it exited. Register our progress and continue.
    3562            0 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3563            0 :                 true
    3564              :             }
    3565            0 :             TenantState::Broken { reason, .. } => {
    3566            0 :                 info!(
    3567            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3568              :                 );
    3569            0 :                 err = Some(SetStoppingError::Broken);
    3570            0 :                 false
    3571              :             }
    3572            0 :             TenantState::Stopping { progress: Some(progress) } => {
    3573            0 :                 info!("Tenant is already in Stopping state");
    3574            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3575            0 :                 false
    3576              :             }
    3577            3 :         });
    3578            3 :         match (stopping, err) {
    3579            3 :             (true, None) => {} // continue
    3580            0 :             (false, Some(err)) => return Err(err),
    3581            0 :             (true, Some(_)) => unreachable!(
    3582            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3583            0 :             ),
    3584            0 :             (false, None) => unreachable!(
    3585            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3586            0 :             ),
    3587              :         }
    3588              : 
    3589            3 :         let timelines_accessor = self.timelines.lock().unwrap();
    3590            3 :         let not_broken_timelines = timelines_accessor
    3591            3 :             .values()
    3592            3 :             .filter(|timeline| !timeline.is_broken());
    3593            6 :         for timeline in not_broken_timelines {
    3594            3 :             timeline.set_state(TimelineState::Stopping);
    3595            3 :         }
    3596            3 :         Ok(())
    3597            3 :     }
    3598              : 
    3599              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3600              :     /// `remove_tenant_from_memory`
    3601              :     ///
    3602              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3603              :     ///
    3604              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3605            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3606            0 :         let mut rx = self.state.subscribe();
    3607            0 : 
    3608            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3609            0 :         // So, wait until it's done.
    3610            0 :         rx.wait_for(|state| match state {
    3611              :             TenantState::Activating(_) | TenantState::Attaching => {
    3612            0 :                 info!(
    3613            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3614            0 :                     <&'static str>::from(state)
    3615              :                 );
    3616            0 :                 false
    3617              :             }
    3618            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3619            0 :         })
    3620            0 :         .await
    3621            0 :         .expect("cannot drop self.state while on a &self method");
    3622            0 : 
    3623            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3624            0 :         self.set_broken_no_wait(reason)
    3625            0 :     }
    3626              : 
    3627            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3628            0 :         let reason = reason.to_string();
    3629            0 :         self.state.send_modify(|current_state| {
    3630            0 :             match *current_state {
    3631              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3632            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3633              :                 }
    3634              :                 TenantState::Active => {
    3635            0 :                     if cfg!(feature = "testing") {
    3636            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3637            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3638              :                     } else {
    3639            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3640              :                     }
    3641              :                 }
    3642              :                 TenantState::Broken { .. } => {
    3643            0 :                     warn!("Tenant is already in Broken state");
    3644              :                 }
    3645              :                 // This is the only "expected" path, any other path is a bug.
    3646              :                 TenantState::Stopping { .. } => {
    3647            0 :                     warn!(
    3648            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3649              :                         reason
    3650              :                     );
    3651            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3652              :                 }
    3653              :            }
    3654            0 :         });
    3655            0 :     }
    3656              : 
    3657            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3658            0 :         self.state.subscribe()
    3659            0 :     }
    3660              : 
    3661              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3662              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3663            0 :     pub(crate) fn activate_now(&self) {
    3664            0 :         self.activate_now_sem.add_permits(1);
    3665            0 :     }
    3666              : 
    3667            0 :     pub(crate) async fn wait_to_become_active(
    3668            0 :         &self,
    3669            0 :         timeout: Duration,
    3670            0 :     ) -> Result<(), GetActiveTenantError> {
    3671            0 :         let mut receiver = self.state.subscribe();
    3672              :         loop {
    3673            0 :             let current_state = receiver.borrow_and_update().clone();
    3674            0 :             match current_state {
    3675              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3676              :                     // in these states, there's a chance that we can reach ::Active
    3677            0 :                     self.activate_now();
    3678            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3679            0 :                         Ok(r) => {
    3680            0 :                             r.map_err(
    3681            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3682              :                                 // Tenant existed but was dropped: report it as non-existent
    3683            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3684            0 :                         )?
    3685              :                         }
    3686              :                         Err(TimeoutCancellableError::Cancelled) => {
    3687            0 :                             return Err(GetActiveTenantError::Cancelled);
    3688              :                         }
    3689              :                         Err(TimeoutCancellableError::Timeout) => {
    3690            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3691            0 :                                 latest_state: Some(self.current_state()),
    3692            0 :                                 wait_time: timeout,
    3693            0 :                             });
    3694              :                         }
    3695              :                     }
    3696              :                 }
    3697              :                 TenantState::Active => {
    3698            0 :                     return Ok(());
    3699              :                 }
    3700            0 :                 TenantState::Broken { reason, .. } => {
    3701            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3702            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3703            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3704              :                 }
    3705              :                 TenantState::Stopping { .. } => {
    3706              :                     // There's no chance the tenant can transition back into ::Active
    3707            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3708              :                 }
    3709              :             }
    3710              :         }
    3711            0 :     }
    3712              : 
    3713            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3714            0 :         self.tenant_conf.load().location.attach_mode
    3715            0 :     }
    3716              : 
    3717              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3718              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3719              :     /// rare external API calls, like a reconciliation at startup.
    3720            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3721            0 :         let attached_tenant_conf = self.tenant_conf.load();
    3722              : 
    3723            0 :         let location_config_mode = match attached_tenant_conf.location.attach_mode {
    3724            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3725            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3726            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3727              :         };
    3728              : 
    3729            0 :         models::LocationConfig {
    3730            0 :             mode: location_config_mode,
    3731            0 :             generation: self.generation.into(),
    3732            0 :             secondary_conf: None,
    3733            0 :             shard_number: self.shard_identity.number.0,
    3734            0 :             shard_count: self.shard_identity.count.literal(),
    3735            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3736            0 :             tenant_conf: attached_tenant_conf.tenant_conf.clone(),
    3737            0 :         }
    3738            0 :     }
    3739              : 
    3740            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3741            0 :         &self.tenant_shard_id
    3742            0 :     }
    3743              : 
    3744          118 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3745          118 :         self.shard_identity.stripe_size
    3746          118 :     }
    3747              : 
    3748            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3749            0 :         self.generation
    3750            0 :     }
    3751              : 
    3752              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3753              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3754              :     /// resetting this tenant to a valid state if we fail.
    3755            0 :     pub(crate) async fn split_prepare(
    3756            0 :         &self,
    3757            0 :         child_shards: &Vec<TenantShardId>,
    3758            0 :     ) -> anyhow::Result<()> {
    3759            0 :         let (timelines, offloaded) = {
    3760            0 :             let timelines = self.timelines.lock().unwrap();
    3761            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3762            0 :             (timelines.clone(), offloaded.clone())
    3763            0 :         };
    3764            0 :         let timelines_iter = timelines
    3765            0 :             .values()
    3766            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3767            0 :             .chain(
    3768            0 :                 offloaded
    3769            0 :                     .values()
    3770            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3771            0 :             );
    3772            0 :         for timeline in timelines_iter {
    3773              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3774              :             // to ensure that they do not start a split if currently in the process of doing these.
    3775              : 
    3776            0 :             let timeline_id = timeline.timeline_id();
    3777              : 
    3778            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3779              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3780              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3781              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3782            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3783            0 :                 timeline
    3784            0 :                     .remote_client
    3785            0 :                     .schedule_index_upload_for_file_changes()?;
    3786            0 :                 timeline.remote_client.wait_completion().await?;
    3787            0 :             }
    3788              : 
    3789            0 :             let remote_client = match timeline {
    3790            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3791            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3792            0 :                     let remote_client = self
    3793            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3794            0 :                     Arc::new(remote_client)
    3795              :                 }
    3796              :             };
    3797              : 
    3798              :             // Shut down the timeline's remote client: this means that the indices we write
    3799              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3800            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3801            0 :             remote_client.shutdown().await;
    3802              : 
    3803              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3804              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3805              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3806              :             // we use here really is the remotely persistent one).
    3807            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3808            0 :             let result = remote_client
    3809            0 :                 .download_index_file(&self.cancel)
    3810            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))
    3811            0 :                 .await?;
    3812            0 :             let index_part = match result {
    3813              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3814            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3815              :                 }
    3816            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3817              :             };
    3818              : 
    3819              :             // A shard split may not take place while a timeline import is on-going
    3820              :             // for the tenant. Timeline imports run as part of each tenant shard
    3821              :             // and rely on the sharding scheme to split the work among pageservers.
    3822              :             // If we were to split in the middle of this process, we would have to
    3823              :             // either ensure that it's driven to completion on the old shard set
    3824              :             // or transfer it to the new shard set. It's technically possible, but complex.
    3825            0 :             match index_part.import_pgdata {
    3826            0 :                 Some(ref import) if !import.is_done() => {
    3827            0 :                     anyhow::bail!(
    3828            0 :                         "Cannot split due to import with idempotency key: {:?}",
    3829            0 :                         import.idempotency_key()
    3830            0 :                     );
    3831              :                 }
    3832            0 :                 Some(_) | None => {
    3833            0 :                     // fallthrough
    3834            0 :                 }
    3835              :             }
    3836              : 
    3837            0 :             for child_shard in child_shards {
    3838            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3839            0 :                 upload_index_part(
    3840            0 :                     &self.remote_storage,
    3841            0 :                     child_shard,
    3842            0 :                     &timeline_id,
    3843            0 :                     self.generation,
    3844            0 :                     &index_part,
    3845            0 :                     &self.cancel,
    3846            0 :                 )
    3847            0 :                 .await?;
    3848              :             }
    3849              :         }
    3850              : 
    3851            0 :         let tenant_manifest = self.build_tenant_manifest();
    3852            0 :         for child_shard in child_shards {
    3853            0 :             tracing::info!(
    3854            0 :                 "Uploading tenant manifest for child {}",
    3855            0 :                 child_shard.to_index()
    3856              :             );
    3857            0 :             upload_tenant_manifest(
    3858            0 :                 &self.remote_storage,
    3859            0 :                 child_shard,
    3860            0 :                 self.generation,
    3861            0 :                 &tenant_manifest,
    3862            0 :                 &self.cancel,
    3863            0 :             )
    3864            0 :             .await?;
    3865              :         }
    3866              : 
    3867            0 :         Ok(())
    3868            0 :     }
    3869              : 
    3870            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3871            0 :         let mut result = TopTenantShardItem {
    3872            0 :             id: self.tenant_shard_id,
    3873            0 :             resident_size: 0,
    3874            0 :             physical_size: 0,
    3875            0 :             max_logical_size: 0,
    3876            0 :             max_logical_size_per_shard: 0,
    3877            0 :         };
    3878              : 
    3879            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3880            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3881            0 : 
    3882            0 :             result.physical_size += timeline
    3883            0 :                 .remote_client
    3884            0 :                 .metrics
    3885            0 :                 .remote_physical_size_gauge
    3886            0 :                 .get();
    3887            0 :             result.max_logical_size = std::cmp::max(
    3888            0 :                 result.max_logical_size,
    3889            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3890            0 :             );
    3891            0 :         }
    3892              : 
    3893            0 :         result.max_logical_size_per_shard = result
    3894            0 :             .max_logical_size
    3895            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    3896            0 : 
    3897            0 :         result
    3898            0 :     }
    3899              : }
    3900              : 
    3901              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3902              : /// perform a topological sort, so that the parent of each timeline comes
    3903              : /// before the children.
    3904              : /// E extracts the ancestor from T
    3905              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3906          117 : fn tree_sort_timelines<T, E>(
    3907          117 :     timelines: HashMap<TimelineId, T>,
    3908          117 :     extractor: E,
    3909          117 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3910          117 : where
    3911          117 :     E: Fn(&T) -> Option<TimelineId>,
    3912          117 : {
    3913          117 :     let mut result = Vec::with_capacity(timelines.len());
    3914          117 : 
    3915          117 :     let mut now = Vec::with_capacity(timelines.len());
    3916          117 :     // (ancestor, children)
    3917          117 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3918          117 :         HashMap::with_capacity(timelines.len());
    3919              : 
    3920          120 :     for (timeline_id, value) in timelines {
    3921            3 :         if let Some(ancestor_id) = extractor(&value) {
    3922            1 :             let children = later.entry(ancestor_id).or_default();
    3923            1 :             children.push((timeline_id, value));
    3924            2 :         } else {
    3925            2 :             now.push((timeline_id, value));
    3926            2 :         }
    3927              :     }
    3928              : 
    3929          120 :     while let Some((timeline_id, metadata)) = now.pop() {
    3930            3 :         result.push((timeline_id, metadata));
    3931              :         // All children of this can be loaded now
    3932            3 :         if let Some(mut children) = later.remove(&timeline_id) {
    3933            1 :             now.append(&mut children);
    3934            2 :         }
    3935              :     }
    3936              : 
    3937              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3938          117 :     if !later.is_empty() {
    3939            0 :         for (missing_id, orphan_ids) in later {
    3940            0 :             for (orphan_id, _) in orphan_ids {
    3941            0 :                 error!(
    3942            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    3943              :                 );
    3944              :             }
    3945              :         }
    3946            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3947          117 :     }
    3948          117 : 
    3949          117 :     Ok(result)
    3950          117 : }
    3951              : 
    3952              : impl TenantShard {
    3953            0 :     pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
    3954            0 :         self.tenant_conf.load().tenant_conf.clone()
    3955            0 :     }
    3956              : 
    3957            0 :     pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
    3958            0 :         self.tenant_specific_overrides()
    3959            0 :             .merge(self.conf.default_tenant_conf.clone())
    3960            0 :     }
    3961              : 
    3962            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3963            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3964            0 :         tenant_conf
    3965            0 :             .checkpoint_distance
    3966            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3967            0 :     }
    3968              : 
    3969            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3970            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3971            0 :         tenant_conf
    3972            0 :             .checkpoint_timeout
    3973            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3974            0 :     }
    3975              : 
    3976            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3977            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3978            0 :         tenant_conf
    3979            0 :             .compaction_target_size
    3980            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3981            0 :     }
    3982              : 
    3983            0 :     pub fn get_compaction_period(&self) -> Duration {
    3984            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3985            0 :         tenant_conf
    3986            0 :             .compaction_period
    3987            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3988            0 :     }
    3989              : 
    3990            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3991            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3992            0 :         tenant_conf
    3993            0 :             .compaction_threshold
    3994            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3995            0 :     }
    3996              : 
    3997            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    3998            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3999            0 :         tenant_conf
    4000            0 :             .rel_size_v2_enabled
    4001            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    4002            0 :     }
    4003              : 
    4004            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    4005            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4006            0 :         tenant_conf
    4007            0 :             .compaction_upper_limit
    4008            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    4009            0 :     }
    4010              : 
    4011            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    4012            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4013            0 :         tenant_conf
    4014            0 :             .compaction_l0_first
    4015            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    4016            0 :     }
    4017              : 
    4018            2 :     pub fn get_gc_horizon(&self) -> u64 {
    4019            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4020            2 :         tenant_conf
    4021            2 :             .gc_horizon
    4022            2 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4023            2 :     }
    4024              : 
    4025            0 :     pub fn get_gc_period(&self) -> Duration {
    4026            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4027            0 :         tenant_conf
    4028            0 :             .gc_period
    4029            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4030            0 :     }
    4031              : 
    4032            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4033            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4034            0 :         tenant_conf
    4035            0 :             .image_creation_threshold
    4036            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4037            0 :     }
    4038              : 
    4039            2 :     pub fn get_pitr_interval(&self) -> Duration {
    4040            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4041            2 :         tenant_conf
    4042            2 :             .pitr_interval
    4043            2 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4044            2 :     }
    4045              : 
    4046            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4047            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4048            0 :         tenant_conf
    4049            0 :             .min_resident_size_override
    4050            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4051            0 :     }
    4052              : 
    4053            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4054            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4055            0 :         let heatmap_period = tenant_conf
    4056            0 :             .heatmap_period
    4057            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4058            0 :         if heatmap_period.is_zero() {
    4059            0 :             None
    4060              :         } else {
    4061            0 :             Some(heatmap_period)
    4062              :         }
    4063            0 :     }
    4064              : 
    4065            2 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4066            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4067            2 :         tenant_conf
    4068            2 :             .lsn_lease_length
    4069            2 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4070            2 :     }
    4071              : 
    4072            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4073            0 :         if self.conf.timeline_offloading {
    4074            0 :             return true;
    4075            0 :         }
    4076            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4077            0 :         tenant_conf
    4078            0 :             .timeline_offloading
    4079            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4080            0 :     }
    4081              : 
    4082              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4083          118 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4084          118 :         // Collect the offloaded timelines, and sort them for deterministic output.
    4085          118 :         let offloaded_timelines = self
    4086          118 :             .timelines_offloaded
    4087          118 :             .lock()
    4088          118 :             .unwrap()
    4089          118 :             .values()
    4090          118 :             .map(|tli| tli.manifest())
    4091          118 :             .sorted_by_key(|m| m.timeline_id)
    4092          118 :             .collect_vec();
    4093          118 : 
    4094          118 :         TenantManifest {
    4095          118 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4096          118 :             stripe_size: Some(self.get_shard_stripe_size()),
    4097          118 :             offloaded_timelines,
    4098          118 :         }
    4099          118 :     }
    4100              : 
    4101            0 :     pub fn update_tenant_config<
    4102            0 :         F: Fn(
    4103            0 :             pageserver_api::models::TenantConfig,
    4104            0 :         ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
    4105            0 :     >(
    4106            0 :         &self,
    4107            0 :         update: F,
    4108            0 :     ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
    4109            0 :         // Use read-copy-update in order to avoid overwriting the location config
    4110            0 :         // state if this races with [`TenantShard::set_new_location_config`]. Note that
    4111            0 :         // this race is not possible if both request types come from the storage
    4112            0 :         // controller (as they should!) because an exclusive op lock is required
    4113            0 :         // on the storage controller side.
    4114            0 : 
    4115            0 :         self.tenant_conf
    4116            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4117            0 :                 Ok(Arc::new(AttachedTenantConf {
    4118            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4119            0 :                     location: attached_conf.location,
    4120            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4121              :                 }))
    4122            0 :             })?;
    4123              : 
    4124            0 :         let updated = self.tenant_conf.load();
    4125            0 : 
    4126            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    4127            0 :         // Don't hold self.timelines.lock() during the notifies.
    4128            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4129            0 :         // mutexes in struct Timeline in the future.
    4130            0 :         let timelines = self.list_timelines();
    4131            0 :         for timeline in timelines {
    4132            0 :             timeline.tenant_conf_updated(&updated);
    4133            0 :         }
    4134              : 
    4135            0 :         Ok(updated.tenant_conf.clone())
    4136            0 :     }
    4137              : 
    4138            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4139            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4140            0 : 
    4141            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4142            0 : 
    4143            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4144            0 :         // Don't hold self.timelines.lock() during the notifies.
    4145            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4146            0 :         // mutexes in struct Timeline in the future.
    4147            0 :         let timelines = self.list_timelines();
    4148            0 :         for timeline in timelines {
    4149            0 :             timeline.tenant_conf_updated(&new_conf);
    4150            0 :         }
    4151            0 :     }
    4152              : 
    4153          117 :     fn get_pagestream_throttle_config(
    4154          117 :         psconf: &'static PageServerConf,
    4155          117 :         overrides: &pageserver_api::models::TenantConfig,
    4156          117 :     ) -> throttle::Config {
    4157          117 :         overrides
    4158          117 :             .timeline_get_throttle
    4159          117 :             .clone()
    4160          117 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4161          117 :     }
    4162              : 
    4163            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
    4164            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4165            0 :         self.pagestream_throttle.reconfigure(conf)
    4166            0 :     }
    4167              : 
    4168              :     /// Helper function to create a new Timeline struct.
    4169              :     ///
    4170              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4171              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4172              :     /// map.
    4173              :     ///
    4174              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4175              :     /// and we might not have the ancestor present anymore which is fine for to be
    4176              :     /// deleted timelines.
    4177              :     #[allow(clippy::too_many_arguments)]
    4178          233 :     fn create_timeline_struct(
    4179          233 :         &self,
    4180          233 :         new_timeline_id: TimelineId,
    4181          233 :         new_metadata: &TimelineMetadata,
    4182          233 :         previous_heatmap: Option<PreviousHeatmap>,
    4183          233 :         ancestor: Option<Arc<Timeline>>,
    4184          233 :         resources: TimelineResources,
    4185          233 :         cause: CreateTimelineCause,
    4186          233 :         create_idempotency: CreateTimelineIdempotency,
    4187          233 :         gc_compaction_state: Option<GcCompactionState>,
    4188          233 :         rel_size_v2_status: Option<RelSizeMigration>,
    4189          233 :         ctx: &RequestContext,
    4190          233 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4191          233 :         let state = match cause {
    4192              :             CreateTimelineCause::Load => {
    4193          233 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4194          233 :                 anyhow::ensure!(
    4195          233 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4196            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4197              :                 );
    4198          233 :                 TimelineState::Loading
    4199              :             }
    4200            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4201              :         };
    4202              : 
    4203          233 :         let pg_version = new_metadata.pg_version();
    4204          233 : 
    4205          233 :         let timeline = Timeline::new(
    4206          233 :             self.conf,
    4207          233 :             Arc::clone(&self.tenant_conf),
    4208          233 :             new_metadata,
    4209          233 :             previous_heatmap,
    4210          233 :             ancestor,
    4211          233 :             new_timeline_id,
    4212          233 :             self.tenant_shard_id,
    4213          233 :             self.generation,
    4214          233 :             self.shard_identity,
    4215          233 :             self.walredo_mgr.clone(),
    4216          233 :             resources,
    4217          233 :             pg_version,
    4218          233 :             state,
    4219          233 :             self.attach_wal_lag_cooldown.clone(),
    4220          233 :             create_idempotency,
    4221          233 :             gc_compaction_state,
    4222          233 :             rel_size_v2_status,
    4223          233 :             self.cancel.child_token(),
    4224          233 :         );
    4225          233 : 
    4226          233 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4227          233 :             .scope(context::Scope::new_timeline(&timeline))
    4228          233 :             .detached_child();
    4229          233 : 
    4230          233 :         Ok((timeline, timeline_ctx))
    4231          233 :     }
    4232              : 
    4233              :     /// [`TenantShard::shutdown`] must be called before dropping the returned [`TenantShard`] object
    4234              :     /// to ensure proper cleanup of background tasks and metrics.
    4235              :     //
    4236              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4237              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4238              :     #[allow(clippy::too_many_arguments)]
    4239          117 :     fn new(
    4240          117 :         state: TenantState,
    4241          117 :         conf: &'static PageServerConf,
    4242          117 :         attached_conf: AttachedTenantConf,
    4243          117 :         shard_identity: ShardIdentity,
    4244          117 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4245          117 :         tenant_shard_id: TenantShardId,
    4246          117 :         remote_storage: GenericRemoteStorage,
    4247          117 :         deletion_queue_client: DeletionQueueClient,
    4248          117 :         l0_flush_global_state: L0FlushGlobalState,
    4249          117 :         basebackup_prepare_sender: BasebackupPrepareSender,
    4250          117 :     ) -> TenantShard {
    4251          117 :         assert!(!attached_conf.location.generation.is_none());
    4252              : 
    4253          117 :         let (state, mut rx) = watch::channel(state);
    4254          117 : 
    4255          117 :         tokio::spawn(async move {
    4256          117 :             // reflect tenant state in metrics:
    4257          117 :             // - global per tenant state: TENANT_STATE_METRIC
    4258          117 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4259          117 :             //
    4260          117 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4261          117 :             // alerting.
    4262          117 : 
    4263          117 :             let tid = tenant_shard_id.to_string();
    4264          117 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4265          117 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4266              : 
    4267          233 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4268          233 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4269          233 :             }
    4270              : 
    4271          117 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4272          117 : 
    4273          117 :             let is_broken = tuple.1;
    4274          117 :             let mut counted_broken = if is_broken {
    4275              :                 // add the id to the set right away, there should not be any updates on the channel
    4276              :                 // after before tenant is removed, if ever
    4277            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4278            0 :                 true
    4279              :             } else {
    4280          117 :                 false
    4281              :             };
    4282              : 
    4283              :             loop {
    4284          233 :                 let labels = &tuple.0;
    4285          233 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4286          233 :                 current.inc();
    4287          233 : 
    4288          233 :                 if rx.changed().await.is_err() {
    4289              :                     // tenant has been dropped
    4290            7 :                     current.dec();
    4291            7 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4292            7 :                     break;
    4293          116 :                 }
    4294          116 : 
    4295          116 :                 current.dec();
    4296          116 :                 tuple = inspect_state(&rx.borrow_and_update());
    4297          116 : 
    4298          116 :                 let is_broken = tuple.1;
    4299          116 :                 if is_broken && !counted_broken {
    4300            0 :                     counted_broken = true;
    4301            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4302            0 :                     // access
    4303            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4304          116 :                 }
    4305              :             }
    4306          117 :         });
    4307          117 : 
    4308          117 :         TenantShard {
    4309          117 :             tenant_shard_id,
    4310          117 :             shard_identity,
    4311          117 :             generation: attached_conf.location.generation,
    4312          117 :             conf,
    4313          117 :             // using now here is good enough approximation to catch tenants with really long
    4314          117 :             // activation times.
    4315          117 :             constructed_at: Instant::now(),
    4316          117 :             timelines: Mutex::new(HashMap::new()),
    4317          117 :             timelines_creating: Mutex::new(HashSet::new()),
    4318          117 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4319          117 :             timelines_importing: Mutex::new(HashMap::new()),
    4320          117 :             remote_tenant_manifest: Default::default(),
    4321          117 :             gc_cs: tokio::sync::Mutex::new(()),
    4322          117 :             walredo_mgr,
    4323          117 :             remote_storage,
    4324          117 :             deletion_queue_client,
    4325          117 :             state,
    4326          117 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4327          117 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4328          117 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4329          117 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4330          117 :                 format!("compaction-{tenant_shard_id}"),
    4331          117 :                 5,
    4332          117 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4333          117 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4334          117 :                 // use an extremely long backoff.
    4335          117 :                 Some(Duration::from_secs(3600 * 24)),
    4336          117 :             )),
    4337          117 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4338          117 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4339          117 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4340          117 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4341          117 :             cancel: CancellationToken::default(),
    4342          117 :             gate: Gate::default(),
    4343          117 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4344          117 :                 TenantShard::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4345          117 :             )),
    4346          117 :             pagestream_throttle_metrics: Arc::new(
    4347          117 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4348          117 :             ),
    4349          117 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4350          117 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4351          117 :             gc_block: Default::default(),
    4352          117 :             l0_flush_global_state,
    4353          117 :             basebackup_prepare_sender,
    4354          117 :         }
    4355          117 :     }
    4356              : 
    4357              :     /// Locate and load config
    4358            0 :     pub(super) fn load_tenant_config(
    4359            0 :         conf: &'static PageServerConf,
    4360            0 :         tenant_shard_id: &TenantShardId,
    4361            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4362            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4363            0 : 
    4364            0 :         info!("loading tenant configuration from {config_path}");
    4365              : 
    4366              :         // load and parse file
    4367            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4368            0 :             match e.kind() {
    4369              :                 std::io::ErrorKind::NotFound => {
    4370              :                     // The config should almost always exist for a tenant directory:
    4371              :                     //  - When attaching a tenant, the config is the first thing we write
    4372              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4373              :                     //    before deleting contents.
    4374              :                     //
    4375              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4376              :                     // between creating directory and writing config.  Callers should handle that as if the
    4377              :                     // directory didn't exist.
    4378              : 
    4379            0 :                     LoadConfigError::NotFound(config_path)
    4380              :                 }
    4381              :                 _ => {
    4382              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4383              :                     // that we cannot cleanly recover
    4384            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4385              :                 }
    4386              :             }
    4387            0 :         })?;
    4388              : 
    4389            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4390            0 :     }
    4391              : 
    4392              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4393              :     pub(super) async fn persist_tenant_config(
    4394              :         conf: &'static PageServerConf,
    4395              :         tenant_shard_id: &TenantShardId,
    4396              :         location_conf: &LocationConf,
    4397              :     ) -> std::io::Result<()> {
    4398              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4399              : 
    4400              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4401              :     }
    4402              : 
    4403              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4404              :     pub(super) async fn persist_tenant_config_at(
    4405              :         tenant_shard_id: &TenantShardId,
    4406              :         config_path: &Utf8Path,
    4407              :         location_conf: &LocationConf,
    4408              :     ) -> std::io::Result<()> {
    4409              :         debug!("persisting tenantconf to {config_path}");
    4410              : 
    4411              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4412              : #  It is read in case of pageserver restart.
    4413              : "#
    4414              :         .to_string();
    4415              : 
    4416            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4417            0 :             Err(std::io::Error::other("tenant-config-before-write"))
    4418            0 :         });
    4419              : 
    4420              :         // Convert the config to a toml file.
    4421              :         conf_content +=
    4422              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4423              : 
    4424              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4425              : 
    4426              :         let conf_content = conf_content.into_bytes();
    4427              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4428              :     }
    4429              : 
    4430              :     //
    4431              :     // How garbage collection works:
    4432              :     //
    4433              :     //                    +--bar------------->
    4434              :     //                   /
    4435              :     //             +----+-----foo---------------->
    4436              :     //            /
    4437              :     // ----main--+-------------------------->
    4438              :     //                \
    4439              :     //                 +-----baz-------->
    4440              :     //
    4441              :     //
    4442              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4443              :     //    `gc_infos` are being refreshed
    4444              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4445              :     //    all the points where other timelines have been branched off.
    4446              :     //    We will refrain from removing page versions at those LSNs.
    4447              :     // 3. For each timeline, scan all layer files on the timeline.
    4448              :     //    Remove all files for which a newer file exists and which
    4449              :     //    don't cover any branch point LSNs.
    4450              :     //
    4451              :     // TODO:
    4452              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4453              :     //   don't need to keep that in the parent anymore. But currently
    4454              :     //   we do.
    4455            2 :     async fn gc_iteration_internal(
    4456            2 :         &self,
    4457            2 :         target_timeline_id: Option<TimelineId>,
    4458            2 :         horizon: u64,
    4459            2 :         pitr: Duration,
    4460            2 :         cancel: &CancellationToken,
    4461            2 :         ctx: &RequestContext,
    4462            2 :     ) -> Result<GcResult, GcError> {
    4463            2 :         let mut totals: GcResult = Default::default();
    4464            2 :         let now = Instant::now();
    4465              : 
    4466            2 :         let gc_timelines = self
    4467            2 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4468            2 :             .await?;
    4469              : 
    4470            2 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4471              : 
    4472              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4473            2 :         if !gc_timelines.is_empty() {
    4474            2 :             info!("{} timelines need GC", gc_timelines.len());
    4475              :         } else {
    4476            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4477              :         }
    4478              : 
    4479              :         // Perform GC for each timeline.
    4480              :         //
    4481              :         // Note that we don't hold the `TenantShard::gc_cs` lock here because we don't want to delay the
    4482              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4483              :         // with branch creation.
    4484              :         //
    4485              :         // See comments in [`TenantShard::branch_timeline`] for more information about why branch
    4486              :         // creation task can run concurrently with timeline's GC iteration.
    4487            4 :         for timeline in gc_timelines {
    4488            2 :             if cancel.is_cancelled() {
    4489              :                 // We were requested to shut down. Stop and return with the progress we
    4490              :                 // made.
    4491            0 :                 break;
    4492            2 :             }
    4493            2 :             let result = match timeline.gc().await {
    4494              :                 Err(GcError::TimelineCancelled) => {
    4495            0 :                     if target_timeline_id.is_some() {
    4496              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4497            0 :                         return Err(GcError::TimelineCancelled);
    4498              :                     } else {
    4499              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4500              :                         // skip past this and proceed to try GC on other timelines.
    4501            0 :                         continue;
    4502              :                     }
    4503              :                 }
    4504            2 :                 r => r?,
    4505              :             };
    4506            2 :             totals += result;
    4507              :         }
    4508              : 
    4509            2 :         totals.elapsed = now.elapsed();
    4510            2 :         Ok(totals)
    4511            2 :     }
    4512              : 
    4513              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4514              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4515              :     /// [`TenantShard::get_gc_horizon`].
    4516              :     ///
    4517              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4518            2 :     pub(crate) async fn refresh_gc_info(
    4519            2 :         &self,
    4520            2 :         cancel: &CancellationToken,
    4521            2 :         ctx: &RequestContext,
    4522            2 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4523            2 :         // since this method can now be called at different rates than the configured gc loop, it
    4524            2 :         // might be that these configuration values get applied faster than what it was previously,
    4525            2 :         // since these were only read from the gc task.
    4526            2 :         let horizon = self.get_gc_horizon();
    4527            2 :         let pitr = self.get_pitr_interval();
    4528            2 : 
    4529            2 :         // refresh all timelines
    4530            2 :         let target_timeline_id = None;
    4531            2 : 
    4532            2 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4533            2 :             .await
    4534            2 :     }
    4535              : 
    4536              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4537              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4538              :     ///
    4539              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4540            0 :     fn initialize_gc_info(
    4541            0 :         &self,
    4542            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4543            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4544            0 :         restrict_to_timeline: Option<TimelineId>,
    4545            0 :     ) {
    4546            0 :         if restrict_to_timeline.is_none() {
    4547              :             // This function must be called before activation: after activation timeline create/delete operations
    4548              :             // might happen, and this function is not safe to run concurrently with those.
    4549            0 :             assert!(!self.is_active());
    4550            0 :         }
    4551              : 
    4552              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4553              :         // the branch point where it was created.
    4554            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4555            0 :             BTreeMap::new();
    4556            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4557            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4558            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4559            0 :                 ancestor_children.push((
    4560            0 :                     timeline_entry.get_ancestor_lsn(),
    4561            0 :                     *timeline_id,
    4562            0 :                     MaybeOffloaded::No,
    4563            0 :                 ));
    4564            0 :             }
    4565            0 :         });
    4566            0 :         timelines_offloaded
    4567            0 :             .iter()
    4568            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4569            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4570            0 :                     return;
    4571              :                 };
    4572            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4573            0 :                     return;
    4574              :                 };
    4575            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4576            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4577            0 :             });
    4578            0 : 
    4579            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4580            0 :         let horizon = self.get_gc_horizon();
    4581              : 
    4582              :         // Populate each timeline's GcInfo with information about its child branches
    4583            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4584            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4585              :         } else {
    4586            0 :             itertools::Either::Right(timelines.values())
    4587              :         };
    4588            0 :         for timeline in timelines_to_write {
    4589            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4590            0 :                 .remove(&timeline.timeline_id)
    4591            0 :                 .unwrap_or_default();
    4592            0 : 
    4593            0 :             branchpoints.sort_by_key(|b| b.0);
    4594            0 : 
    4595            0 :             let mut target = timeline.gc_info.write().unwrap();
    4596            0 : 
    4597            0 :             target.retain_lsns = branchpoints;
    4598            0 : 
    4599            0 :             let space_cutoff = timeline
    4600            0 :                 .get_last_record_lsn()
    4601            0 :                 .checked_sub(horizon)
    4602            0 :                 .unwrap_or(Lsn(0));
    4603            0 : 
    4604            0 :             target.cutoffs = GcCutoffs {
    4605            0 :                 space: space_cutoff,
    4606            0 :                 time: None,
    4607            0 :             };
    4608            0 :         }
    4609            0 :     }
    4610              : 
    4611            4 :     async fn refresh_gc_info_internal(
    4612            4 :         &self,
    4613            4 :         target_timeline_id: Option<TimelineId>,
    4614            4 :         horizon: u64,
    4615            4 :         pitr: Duration,
    4616            4 :         cancel: &CancellationToken,
    4617            4 :         ctx: &RequestContext,
    4618            4 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4619            4 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4620            4 :         // currently visible timelines.
    4621            4 :         let timelines = self
    4622            4 :             .timelines
    4623            4 :             .lock()
    4624            4 :             .unwrap()
    4625            4 :             .values()
    4626           10 :             .filter(|tl| match target_timeline_id.as_ref() {
    4627            2 :                 Some(target) => &tl.timeline_id == target,
    4628            8 :                 None => true,
    4629           10 :             })
    4630            4 :             .cloned()
    4631            4 :             .collect::<Vec<_>>();
    4632            4 : 
    4633            4 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4634              :             // We were to act on a particular timeline and it wasn't found
    4635            0 :             return Err(GcError::TimelineNotFound);
    4636            4 :         }
    4637            4 : 
    4638            4 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4639            4 :             HashMap::with_capacity(timelines.len());
    4640            4 : 
    4641            4 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4642            4 :         let now_ts_for_pitr_calc = SystemTime::now();
    4643           10 :         for timeline in timelines.iter() {
    4644           10 :             let ctx = &ctx.with_scope_timeline(timeline);
    4645           10 :             let cutoff = timeline
    4646           10 :                 .get_last_record_lsn()
    4647           10 :                 .checked_sub(horizon)
    4648           10 :                 .unwrap_or(Lsn(0));
    4649              : 
    4650           10 :             let cutoffs = timeline
    4651           10 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4652           10 :                 .await?;
    4653           10 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4654           10 :             assert!(old.is_none());
    4655              :         }
    4656              : 
    4657            4 :         if !self.is_active() || self.cancel.is_cancelled() {
    4658            0 :             return Err(GcError::TenantCancelled);
    4659            4 :         }
    4660              : 
    4661              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4662              :         // because that will stall branch creation.
    4663            4 :         let gc_cs = self.gc_cs.lock().await;
    4664              : 
    4665              :         // Ok, we now know all the branch points.
    4666              :         // Update the GC information for each timeline.
    4667            4 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4668           14 :         for timeline in timelines {
    4669              :             // We filtered the timeline list above
    4670           10 :             if let Some(target_timeline_id) = target_timeline_id {
    4671            2 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4672            8 :             }
    4673              : 
    4674              :             {
    4675           10 :                 let mut target = timeline.gc_info.write().unwrap();
    4676           10 : 
    4677           10 :                 // Cull any expired leases
    4678           10 :                 let now = SystemTime::now();
    4679           10 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4680           10 : 
    4681           10 :                 timeline
    4682           10 :                     .metrics
    4683           10 :                     .valid_lsn_lease_count_gauge
    4684           10 :                     .set(target.leases.len() as u64);
    4685              : 
    4686              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4687           10 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4688            6 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4689            6 :                         target.within_ancestor_pitr =
    4690            6 :                             Some(timeline.get_ancestor_lsn()) >= ancestor_gc_cutoffs.time;
    4691            6 :                     }
    4692            4 :                 }
    4693              : 
    4694              :                 // Update metrics that depend on GC state
    4695           10 :                 timeline
    4696           10 :                     .metrics
    4697           10 :                     .archival_size
    4698           10 :                     .set(if target.within_ancestor_pitr {
    4699            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4700              :                     } else {
    4701           10 :                         0
    4702              :                     });
    4703           10 :                 if let Some(time_cutoff) = target.cutoffs.time {
    4704            4 :                     timeline.metrics.pitr_history_size.set(
    4705            4 :                         timeline
    4706            4 :                             .get_last_record_lsn()
    4707            4 :                             .checked_sub(time_cutoff)
    4708            4 :                             .unwrap_or_default()
    4709            4 :                             .0,
    4710            4 :                     );
    4711            6 :                 }
    4712              : 
    4713              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4714              :                 // - this timeline was created while we were finding cutoffs
    4715              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4716           10 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4717           10 :                     let original_cutoffs = target.cutoffs.clone();
    4718           10 :                     // GC cutoffs should never go back
    4719           10 :                     target.cutoffs = GcCutoffs {
    4720           10 :                         space: cutoffs.space.max(original_cutoffs.space),
    4721           10 :                         time: cutoffs.time.max(original_cutoffs.time),
    4722           10 :                     }
    4723            0 :                 }
    4724              :             }
    4725              : 
    4726           10 :             gc_timelines.push(timeline);
    4727              :         }
    4728            4 :         drop(gc_cs);
    4729            4 :         Ok(gc_timelines)
    4730            4 :     }
    4731              : 
    4732              :     /// A substitute for `branch_timeline` for use in unit tests.
    4733              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4734              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4735              :     /// timeline background tasks are launched, except the flush loop.
    4736              :     #[cfg(test)]
    4737          119 :     async fn branch_timeline_test(
    4738          119 :         self: &Arc<Self>,
    4739          119 :         src_timeline: &Arc<Timeline>,
    4740          119 :         dst_id: TimelineId,
    4741          119 :         ancestor_lsn: Option<Lsn>,
    4742          119 :         ctx: &RequestContext,
    4743          119 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4744          119 :         let tl = self
    4745          119 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4746          119 :             .await?
    4747          117 :             .into_timeline_for_test();
    4748          117 :         tl.set_state(TimelineState::Active);
    4749          117 :         Ok(tl)
    4750          119 :     }
    4751              : 
    4752              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4753              :     #[cfg(test)]
    4754              :     #[allow(clippy::too_many_arguments)]
    4755            6 :     pub async fn branch_timeline_test_with_layers(
    4756            6 :         self: &Arc<Self>,
    4757            6 :         src_timeline: &Arc<Timeline>,
    4758            6 :         dst_id: TimelineId,
    4759            6 :         ancestor_lsn: Option<Lsn>,
    4760            6 :         ctx: &RequestContext,
    4761            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4762            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4763            6 :         end_lsn: Lsn,
    4764            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4765              :         use checks::check_valid_layermap;
    4766              :         use itertools::Itertools;
    4767              : 
    4768            6 :         let tline = self
    4769            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4770            6 :             .await?;
    4771            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4772            6 :             ancestor_lsn
    4773              :         } else {
    4774            0 :             tline.get_last_record_lsn()
    4775              :         };
    4776            6 :         assert!(end_lsn >= ancestor_lsn);
    4777            6 :         tline.force_advance_lsn(end_lsn);
    4778            9 :         for deltas in delta_layer_desc {
    4779            3 :             tline
    4780            3 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4781            3 :                 .await?;
    4782              :         }
    4783            8 :         for (lsn, images) in image_layer_desc {
    4784            2 :             tline
    4785            2 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4786            2 :                 .await?;
    4787              :         }
    4788            6 :         let layer_names = tline
    4789            6 :             .layers
    4790            6 :             .read()
    4791            6 :             .await
    4792            6 :             .layer_map()
    4793            6 :             .unwrap()
    4794            6 :             .iter_historic_layers()
    4795            6 :             .map(|layer| layer.layer_name())
    4796            6 :             .collect_vec();
    4797            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4798            0 :             bail!("invalid layermap: {err}");
    4799            6 :         }
    4800            6 :         Ok(tline)
    4801            6 :     }
    4802              : 
    4803              :     /// Branch an existing timeline.
    4804            0 :     async fn branch_timeline(
    4805            0 :         self: &Arc<Self>,
    4806            0 :         src_timeline: &Arc<Timeline>,
    4807            0 :         dst_id: TimelineId,
    4808            0 :         start_lsn: Option<Lsn>,
    4809            0 :         ctx: &RequestContext,
    4810            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4811            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4812            0 :             .await
    4813            0 :     }
    4814              : 
    4815          119 :     async fn branch_timeline_impl(
    4816          119 :         self: &Arc<Self>,
    4817          119 :         src_timeline: &Arc<Timeline>,
    4818          119 :         dst_id: TimelineId,
    4819          119 :         start_lsn: Option<Lsn>,
    4820          119 :         ctx: &RequestContext,
    4821          119 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4822          119 :         let src_id = src_timeline.timeline_id;
    4823              : 
    4824              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4825              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4826              :         // valid while we are creating the branch.
    4827          119 :         let _gc_cs = self.gc_cs.lock().await;
    4828              : 
    4829              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4830          119 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4831            1 :             let lsn = src_timeline.get_last_record_lsn();
    4832            1 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4833            1 :             lsn
    4834          119 :         });
    4835              : 
    4836              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4837          119 :         let timeline_create_guard = match self
    4838          119 :             .start_creating_timeline(
    4839          119 :                 dst_id,
    4840          119 :                 CreateTimelineIdempotency::Branch {
    4841          119 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4842          119 :                     ancestor_start_lsn: start_lsn,
    4843          119 :                 },
    4844          119 :             )
    4845          119 :             .await?
    4846              :         {
    4847          119 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4848            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4849            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4850              :             }
    4851              :         };
    4852              : 
    4853              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4854              :         // horizon on the source timeline
    4855              :         //
    4856              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4857              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4858              :         // planned GC cutoff in 'gc_info' is normally larger than
    4859              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    4860              :         // changed the GC settings for the tenant to make the PITR window
    4861              :         // larger, but some of the data was already removed by an earlier GC
    4862              :         // iteration.
    4863              : 
    4864              :         // check against last actual 'latest_gc_cutoff' first
    4865          119 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    4866          119 :         {
    4867          119 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4868          119 :             let planned_cutoff = gc_info.min_cutoff();
    4869          119 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    4870            0 :                 tracing::info!(
    4871            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    4872            0 :                     *applied_gc_cutoff_lsn
    4873              :                 );
    4874              :             } else {
    4875          119 :                 src_timeline
    4876          119 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    4877          119 :                     .context(format!(
    4878          119 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    4879          119 :                         *applied_gc_cutoff_lsn,
    4880          119 :                     ))
    4881          119 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    4882              : 
    4883              :                 // and then the planned GC cutoff
    4884          117 :                 if start_lsn < planned_cutoff {
    4885            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4886            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    4887            0 :                     )));
    4888          117 :                 }
    4889              :             }
    4890              :         }
    4891              : 
    4892              :         //
    4893              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4894              :         // so that GC cannot advance the GC cutoff until we are finished.
    4895              :         // Proceed with the branch creation.
    4896              :         //
    4897              : 
    4898              :         // Determine prev-LSN for the new timeline. We can only determine it if
    4899              :         // the timeline was branched at the current end of the source timeline.
    4900              :         let RecordLsn {
    4901          117 :             last: src_last,
    4902          117 :             prev: src_prev,
    4903          117 :         } = src_timeline.get_last_record_rlsn();
    4904          117 :         let dst_prev = if src_last == start_lsn {
    4905          108 :             Some(src_prev)
    4906              :         } else {
    4907            9 :             None
    4908              :         };
    4909              : 
    4910              :         // Create the metadata file, noting the ancestor of the new timeline.
    4911              :         // There is initially no data in it, but all the read-calls know to look
    4912              :         // into the ancestor.
    4913          117 :         let metadata = TimelineMetadata::new(
    4914          117 :             start_lsn,
    4915          117 :             dst_prev,
    4916          117 :             Some(src_id),
    4917          117 :             start_lsn,
    4918          117 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4919          117 :             src_timeline.initdb_lsn,
    4920          117 :             src_timeline.pg_version,
    4921          117 :         );
    4922              : 
    4923          117 :         let (uninitialized_timeline, _timeline_ctx) = self
    4924          117 :             .prepare_new_timeline(
    4925          117 :                 dst_id,
    4926          117 :                 &metadata,
    4927          117 :                 timeline_create_guard,
    4928          117 :                 start_lsn + 1,
    4929          117 :                 Some(Arc::clone(src_timeline)),
    4930          117 :                 Some(src_timeline.get_rel_size_v2_status()),
    4931          117 :                 ctx,
    4932          117 :             )
    4933          117 :             .await?;
    4934              : 
    4935          117 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    4936              : 
    4937              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4938              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4939              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4940              :         // could get incorrect information and remove more layers, than needed.
    4941              :         // See also https://github.com/neondatabase/neon/issues/3865
    4942          117 :         new_timeline
    4943          117 :             .remote_client
    4944          117 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4945          117 :             .context("branch initial metadata upload")?;
    4946              : 
    4947              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4948              : 
    4949          117 :         Ok(CreateTimelineResult::Created(new_timeline))
    4950          119 :     }
    4951              : 
    4952              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4953              :     #[cfg(test)]
    4954              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4955              :     pub(crate) async fn bootstrap_timeline_test(
    4956              :         self: &Arc<Self>,
    4957              :         timeline_id: TimelineId,
    4958              :         pg_version: u32,
    4959              :         load_existing_initdb: Option<TimelineId>,
    4960              :         ctx: &RequestContext,
    4961              :     ) -> anyhow::Result<Arc<Timeline>> {
    4962              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4963              :             .await
    4964              :             .map_err(anyhow::Error::new)
    4965            1 :             .map(|r| r.into_timeline_for_test())
    4966              :     }
    4967              : 
    4968              :     /// Get exclusive access to the timeline ID for creation.
    4969              :     ///
    4970              :     /// Timeline-creating code paths must use this function before making changes
    4971              :     /// to in-memory or persistent state.
    4972              :     ///
    4973              :     /// The `state` parameter is a description of the timeline creation operation
    4974              :     /// we intend to perform.
    4975              :     /// If the timeline was already created in the meantime, we check whether this
    4976              :     /// request conflicts or is idempotent , based on `state`.
    4977          233 :     async fn start_creating_timeline(
    4978          233 :         self: &Arc<Self>,
    4979          233 :         new_timeline_id: TimelineId,
    4980          233 :         idempotency: CreateTimelineIdempotency,
    4981          233 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4982          233 :         let allow_offloaded = false;
    4983          233 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4984          232 :             Ok(create_guard) => {
    4985          232 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4986          232 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4987              :             }
    4988            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4989              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4990              :                 // Creation is in progress, we cannot create it again, and we cannot
    4991              :                 // check if this request matches the existing one, so caller must try
    4992              :                 // again later.
    4993            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4994              :             }
    4995            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4996              :             Err(TimelineExclusionError::AlreadyExists {
    4997            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4998            0 :                 ..
    4999            0 :             }) => {
    5000            0 :                 info!("timeline already exists but is offloaded");
    5001            0 :                 Err(CreateTimelineError::Conflict)
    5002              :             }
    5003              :             Err(TimelineExclusionError::AlreadyExists {
    5004            1 :                 existing: TimelineOrOffloaded::Timeline(existing),
    5005            1 :                 arg,
    5006            1 :             }) => {
    5007            1 :                 {
    5008            1 :                     let existing = &existing.create_idempotency;
    5009            1 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    5010            1 :                     debug!("timeline already exists");
    5011              : 
    5012            1 :                     match (existing, &arg) {
    5013              :                         // FailWithConflict => no idempotency check
    5014              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5015              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5016            1 :                             warn!("timeline already exists, failing request");
    5017            1 :                             return Err(CreateTimelineError::Conflict);
    5018              :                         }
    5019              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    5020            0 :                         (x, y) if x == y => {
    5021            0 :                             info!(
    5022            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    5023              :                             );
    5024              :                             // fallthrough
    5025              :                         }
    5026              :                         (_, _) => {
    5027            0 :                             warn!("idempotency conflict, failing request");
    5028            0 :                             return Err(CreateTimelineError::Conflict);
    5029              :                         }
    5030              :                     }
    5031              :                 }
    5032              : 
    5033            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5034              :             }
    5035              :         }
    5036          233 :     }
    5037              : 
    5038            0 :     async fn upload_initdb(
    5039            0 :         &self,
    5040            0 :         timelines_path: &Utf8PathBuf,
    5041            0 :         pgdata_path: &Utf8PathBuf,
    5042            0 :         timeline_id: &TimelineId,
    5043            0 :     ) -> anyhow::Result<()> {
    5044            0 :         let temp_path = timelines_path.join(format!(
    5045            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5046            0 :         ));
    5047            0 : 
    5048            0 :         scopeguard::defer! {
    5049            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    5050            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5051            0 :             }
    5052            0 :         }
    5053              : 
    5054            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5055              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5056            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5057            0 :             warn!(
    5058            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5059              :             );
    5060            0 :         }
    5061              : 
    5062            0 :         pausable_failpoint!("before-initdb-upload");
    5063              : 
    5064            0 :         backoff::retry(
    5065            0 :             || async {
    5066            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5067            0 :                     &self.remote_storage,
    5068            0 :                     &self.tenant_shard_id.tenant_id,
    5069            0 :                     timeline_id,
    5070            0 :                     pgdata_zstd.try_clone().await?,
    5071            0 :                     tar_zst_size,
    5072            0 :                     &self.cancel,
    5073            0 :                 )
    5074            0 :                 .await
    5075            0 :             },
    5076            0 :             |_| false,
    5077            0 :             3,
    5078            0 :             u32::MAX,
    5079            0 :             "persist_initdb_tar_zst",
    5080            0 :             &self.cancel,
    5081            0 :         )
    5082            0 :         .await
    5083            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5084            0 :         .and_then(|x| x)
    5085            0 :     }
    5086              : 
    5087              :     /// - run initdb to init temporary instance and get bootstrap data
    5088              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5089            1 :     async fn bootstrap_timeline(
    5090            1 :         self: &Arc<Self>,
    5091            1 :         timeline_id: TimelineId,
    5092            1 :         pg_version: u32,
    5093            1 :         load_existing_initdb: Option<TimelineId>,
    5094            1 :         ctx: &RequestContext,
    5095            1 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5096            1 :         let timeline_create_guard = match self
    5097            1 :             .start_creating_timeline(
    5098            1 :                 timeline_id,
    5099            1 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5100            1 :             )
    5101            1 :             .await?
    5102              :         {
    5103            1 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5104            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5105            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5106              :             }
    5107              :         };
    5108              : 
    5109              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5110              :         // temporary directory for basebackup files for the given timeline.
    5111              : 
    5112            1 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5113            1 :         let pgdata_path = path_with_suffix_extension(
    5114            1 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5115            1 :             TEMP_FILE_SUFFIX,
    5116            1 :         );
    5117            1 : 
    5118            1 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5119            1 :         // we won't race with other creations or existent timelines with the same path.
    5120            1 :         if pgdata_path.exists() {
    5121            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5122            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5123            0 :             })?;
    5124            0 :             tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
    5125            1 :         }
    5126              : 
    5127              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5128            1 :         let pgdata_path_deferred = pgdata_path.clone();
    5129            1 :         scopeguard::defer! {
    5130            1 :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5131            1 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5132            1 :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5133            1 :             } else {
    5134            1 :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5135            1 :             }
    5136            1 :         }
    5137            1 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5138            1 :             if existing_initdb_timeline_id != timeline_id {
    5139            0 :                 let source_path = &remote_initdb_archive_path(
    5140            0 :                     &self.tenant_shard_id.tenant_id,
    5141            0 :                     &existing_initdb_timeline_id,
    5142            0 :                 );
    5143            0 :                 let dest_path =
    5144            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5145            0 : 
    5146            0 :                 // if this fails, it will get retried by retried control plane requests
    5147            0 :                 self.remote_storage
    5148            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5149            0 :                     .await
    5150            0 :                     .context("copy initdb tar")?;
    5151            1 :             }
    5152            1 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5153            1 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5154            1 :                     self.conf,
    5155            1 :                     &self.remote_storage,
    5156            1 :                     &self.tenant_shard_id,
    5157            1 :                     &existing_initdb_timeline_id,
    5158            1 :                     &self.cancel,
    5159            1 :                 )
    5160            1 :                 .await
    5161            1 :                 .context("download initdb tar")?;
    5162              : 
    5163            1 :             scopeguard::defer! {
    5164            1 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5165            1 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5166            1 :                 }
    5167            1 :             }
    5168            1 : 
    5169            1 :             let buf_read =
    5170            1 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5171            1 :             extract_zst_tarball(&pgdata_path, buf_read)
    5172            1 :                 .await
    5173            1 :                 .context("extract initdb tar")?;
    5174              :         } else {
    5175              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5176            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5177            0 :                 .await
    5178            0 :                 .context("run initdb")?;
    5179              : 
    5180              :             // Upload the created data dir to S3
    5181            0 :             if self.tenant_shard_id().is_shard_zero() {
    5182            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5183            0 :                     .await?;
    5184            0 :             }
    5185              :         }
    5186            1 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5187            1 : 
    5188            1 :         // Import the contents of the data directory at the initial checkpoint
    5189            1 :         // LSN, and any WAL after that.
    5190            1 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5191            1 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5192            1 :         let new_metadata = TimelineMetadata::new(
    5193            1 :             Lsn(0),
    5194            1 :             None,
    5195            1 :             None,
    5196            1 :             Lsn(0),
    5197            1 :             pgdata_lsn,
    5198            1 :             pgdata_lsn,
    5199            1 :             pg_version,
    5200            1 :         );
    5201            1 :         let (mut raw_timeline, timeline_ctx) = self
    5202            1 :             .prepare_new_timeline(
    5203            1 :                 timeline_id,
    5204            1 :                 &new_metadata,
    5205            1 :                 timeline_create_guard,
    5206            1 :                 pgdata_lsn,
    5207            1 :                 None,
    5208            1 :                 None,
    5209            1 :                 ctx,
    5210            1 :             )
    5211            1 :             .await?;
    5212              : 
    5213            1 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5214            1 :         raw_timeline
    5215            1 :             .write(|unfinished_timeline| async move {
    5216            1 :                 import_datadir::import_timeline_from_postgres_datadir(
    5217            1 :                     &unfinished_timeline,
    5218            1 :                     &pgdata_path,
    5219            1 :                     pgdata_lsn,
    5220            1 :                     &timeline_ctx,
    5221            1 :                 )
    5222            1 :                 .await
    5223            1 :                 .with_context(|| {
    5224            0 :                     format!(
    5225            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5226            0 :                     )
    5227            1 :                 })?;
    5228              : 
    5229            1 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5230            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5231            0 :                         "failpoint before-checkpoint-new-timeline"
    5232            0 :                     )))
    5233            1 :                 });
    5234              : 
    5235            1 :                 Ok(())
    5236            2 :             })
    5237            1 :             .await?;
    5238              : 
    5239              :         // All done!
    5240            1 :         let timeline = raw_timeline.finish_creation().await?;
    5241              : 
    5242              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5243              : 
    5244            1 :         Ok(CreateTimelineResult::Created(timeline))
    5245            1 :     }
    5246              : 
    5247          230 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5248          230 :         RemoteTimelineClient::new(
    5249          230 :             self.remote_storage.clone(),
    5250          230 :             self.deletion_queue_client.clone(),
    5251          230 :             self.conf,
    5252          230 :             self.tenant_shard_id,
    5253          230 :             timeline_id,
    5254          230 :             self.generation,
    5255          230 :             &self.tenant_conf.load().location,
    5256          230 :         )
    5257          230 :     }
    5258              : 
    5259              :     /// Builds required resources for a new timeline.
    5260          230 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5261          230 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5262          230 :         self.get_timeline_resources_for(remote_client)
    5263          230 :     }
    5264              : 
    5265              :     /// Builds timeline resources for the given remote client.
    5266          233 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5267          233 :         TimelineResources {
    5268          233 :             remote_client,
    5269          233 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5270          233 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5271          233 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5272          233 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5273          233 :             basebackup_prepare_sender: self.basebackup_prepare_sender.clone(),
    5274          233 :         }
    5275          233 :     }
    5276              : 
    5277              :     /// Creates intermediate timeline structure and its files.
    5278              :     ///
    5279              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5280              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5281              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5282              :     #[allow(clippy::too_many_arguments)]
    5283          230 :     async fn prepare_new_timeline<'a>(
    5284          230 :         &'a self,
    5285          230 :         new_timeline_id: TimelineId,
    5286          230 :         new_metadata: &TimelineMetadata,
    5287          230 :         create_guard: TimelineCreateGuard,
    5288          230 :         start_lsn: Lsn,
    5289          230 :         ancestor: Option<Arc<Timeline>>,
    5290          230 :         rel_size_v2_status: Option<RelSizeMigration>,
    5291          230 :         ctx: &RequestContext,
    5292          230 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5293          230 :         let tenant_shard_id = self.tenant_shard_id;
    5294          230 : 
    5295          230 :         let resources = self.build_timeline_resources(new_timeline_id);
    5296          230 :         resources
    5297          230 :             .remote_client
    5298          230 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5299              : 
    5300          230 :         let (timeline_struct, timeline_ctx) = self
    5301          230 :             .create_timeline_struct(
    5302          230 :                 new_timeline_id,
    5303          230 :                 new_metadata,
    5304          230 :                 None,
    5305          230 :                 ancestor,
    5306          230 :                 resources,
    5307          230 :                 CreateTimelineCause::Load,
    5308          230 :                 create_guard.idempotency.clone(),
    5309          230 :                 None,
    5310          230 :                 rel_size_v2_status,
    5311          230 :                 ctx,
    5312          230 :             )
    5313          230 :             .context("Failed to create timeline data structure")?;
    5314              : 
    5315          230 :         timeline_struct.init_empty_layer_map(start_lsn);
    5316              : 
    5317          230 :         if let Err(e) = self
    5318          230 :             .create_timeline_files(&create_guard.timeline_path)
    5319          230 :             .await
    5320              :         {
    5321            0 :             error!(
    5322            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5323              :             );
    5324            0 :             cleanup_timeline_directory(create_guard);
    5325            0 :             return Err(e);
    5326          230 :         }
    5327          230 : 
    5328          230 :         debug!(
    5329            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5330              :         );
    5331              : 
    5332          230 :         Ok((
    5333          230 :             UninitializedTimeline::new(
    5334          230 :                 self,
    5335          230 :                 new_timeline_id,
    5336          230 :                 Some((timeline_struct, create_guard)),
    5337          230 :             ),
    5338          230 :             timeline_ctx,
    5339          230 :         ))
    5340          230 :     }
    5341              : 
    5342          230 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5343          230 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5344              : 
    5345          230 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5346            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5347          230 :         });
    5348              : 
    5349          230 :         Ok(())
    5350          230 :     }
    5351              : 
    5352              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5353              :     /// concurrent attempts to create the same timeline.
    5354              :     ///
    5355              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5356              :     /// offloaded timelines or not.
    5357          233 :     fn create_timeline_create_guard(
    5358          233 :         self: &Arc<Self>,
    5359          233 :         timeline_id: TimelineId,
    5360          233 :         idempotency: CreateTimelineIdempotency,
    5361          233 :         allow_offloaded: bool,
    5362          233 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5363          233 :         let tenant_shard_id = self.tenant_shard_id;
    5364          233 : 
    5365          233 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5366              : 
    5367          233 :         let create_guard = TimelineCreateGuard::new(
    5368          233 :             self,
    5369          233 :             timeline_id,
    5370          233 :             timeline_path.clone(),
    5371          233 :             idempotency,
    5372          233 :             allow_offloaded,
    5373          233 :         )?;
    5374              : 
    5375              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5376              :         // for creation.
    5377              :         // A timeline directory should never exist on disk already:
    5378              :         // - a previous failed creation would have cleaned up after itself
    5379              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5380              :         //
    5381              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5382              :         // this error may indicate a bug in cleanup on failed creations.
    5383          232 :         if timeline_path.exists() {
    5384            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5385            0 :                 "Timeline directory already exists! This is a bug."
    5386            0 :             )));
    5387          232 :         }
    5388          232 : 
    5389          232 :         Ok(create_guard)
    5390          233 :     }
    5391              : 
    5392              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5393              :     ///
    5394              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5395              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5396              :     pub async fn gather_size_inputs(
    5397              :         &self,
    5398              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5399              :         // (only if it is shorter than the real cutoff).
    5400              :         max_retention_period: Option<u64>,
    5401              :         cause: LogicalSizeCalculationCause,
    5402              :         cancel: &CancellationToken,
    5403              :         ctx: &RequestContext,
    5404              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5405              :         let logical_sizes_at_once = self
    5406              :             .conf
    5407              :             .concurrent_tenant_size_logical_size_queries
    5408              :             .inner();
    5409              : 
    5410              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5411              :         //
    5412              :         // But the only case where we need to run multiple of these at once is when we
    5413              :         // request a size for a tenant manually via API, while another background calculation
    5414              :         // is in progress (which is not a common case).
    5415              :         //
    5416              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5417              :         let mut shared_cache = tokio::select! {
    5418              :             locked = self.cached_logical_sizes.lock() => locked,
    5419              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5420              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5421              :         };
    5422              : 
    5423              :         size::gather_inputs(
    5424              :             self,
    5425              :             logical_sizes_at_once,
    5426              :             max_retention_period,
    5427              :             &mut shared_cache,
    5428              :             cause,
    5429              :             cancel,
    5430              :             ctx,
    5431              :         )
    5432              :         .await
    5433              :     }
    5434              : 
    5435              :     /// Calculate synthetic tenant size and cache the result.
    5436              :     /// This is periodically called by background worker.
    5437              :     /// result is cached in tenant struct
    5438              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5439              :     pub async fn calculate_synthetic_size(
    5440              :         &self,
    5441              :         cause: LogicalSizeCalculationCause,
    5442              :         cancel: &CancellationToken,
    5443              :         ctx: &RequestContext,
    5444              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5445              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5446              : 
    5447              :         let size = inputs.calculate();
    5448              : 
    5449              :         self.set_cached_synthetic_size(size);
    5450              : 
    5451              :         Ok(size)
    5452              :     }
    5453              : 
    5454              :     /// Cache given synthetic size and update the metric value
    5455            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5456            0 :         self.cached_synthetic_tenant_size
    5457            0 :             .store(size, Ordering::Relaxed);
    5458            0 : 
    5459            0 :         // Only shard zero should be calculating synthetic sizes
    5460            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5461              : 
    5462            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5463            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5464            0 :             .unwrap()
    5465            0 :             .set(size);
    5466            0 :     }
    5467              : 
    5468            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5469            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5470            0 :     }
    5471              : 
    5472              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5473              :     ///
    5474              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5475              :     /// from an external API handler.
    5476              :     ///
    5477              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5478              :     /// still bounded by tenant/timeline shutdown.
    5479              :     #[tracing::instrument(skip_all)]
    5480              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5481              :         let timelines = self.timelines.lock().unwrap().clone();
    5482              : 
    5483            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5484            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5485            0 :             timeline.freeze_and_flush().await?;
    5486            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5487            0 :             timeline.remote_client.wait_completion().await?;
    5488              : 
    5489            0 :             Ok(())
    5490            0 :         }
    5491              : 
    5492              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5493              :         // aborted when this function's future is cancelled: they should stay alive
    5494              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5495              :         // before Timeline shutdown completes.
    5496              :         let mut results = FuturesUnordered::new();
    5497              : 
    5498              :         for (_timeline_id, timeline) in timelines {
    5499              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5500              :             // means that if this function's future is cancelled, the Timeline shutdown
    5501              :             // will still wait for any I/O in here to complete.
    5502              :             let Ok(gate) = timeline.gate.enter() else {
    5503              :                 continue;
    5504              :             };
    5505            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5506              :             results.push(jh);
    5507              :         }
    5508              : 
    5509              :         while let Some(r) = results.next().await {
    5510              :             if let Err(e) = r {
    5511              :                 if !e.is_cancelled() && !e.is_panic() {
    5512              :                     tracing::error!("unexpected join error: {e:?}");
    5513              :                 }
    5514              :             }
    5515              :         }
    5516              : 
    5517              :         // The flushes we did above were just writes, but the TenantShard might have had
    5518              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5519              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5520              :         // because it's typically a no-op.
    5521              :         match self.deletion_queue_client.flush_execute().await {
    5522              :             Ok(_) => {}
    5523              :             Err(DeletionQueueError::ShuttingDown) => {}
    5524              :         }
    5525              : 
    5526              :         Ok(())
    5527              :     }
    5528              : 
    5529            0 :     pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
    5530            0 :         self.tenant_conf.load().tenant_conf.clone()
    5531            0 :     }
    5532              : 
    5533              :     /// How much local storage would this tenant like to have?  It can cope with
    5534              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5535              :     /// the TenantShard to advertise how much storage it would prefer to have to provide fast I/O
    5536              :     /// by keeping important things on local disk.
    5537              :     ///
    5538              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5539              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5540              :     /// actually use more than they report here.
    5541            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5542            0 :         let timelines = self.timelines.lock().unwrap();
    5543            0 : 
    5544            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5545            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5546            0 :         // of them is used actively enough to occupy space on disk.
    5547            0 :         timelines
    5548            0 :             .values()
    5549            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5550            0 :             .max()
    5551            0 :             .unwrap_or(0)
    5552            0 :     }
    5553              : 
    5554              :     /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
    5555              :     /// manifest in `Self::remote_tenant_manifest`.
    5556              :     ///
    5557              :     /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
    5558              :     /// changing any `TenantShard` state that's included in the manifest, consider making the manifest
    5559              :     /// the authoritative source of data with an API that automatically uploads on changes. Revisit
    5560              :     /// this when the manifest is more widely used and we have a better idea of the data model.
    5561          118 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5562              :         // Multiple tasks may call this function concurrently after mutating the TenantShard runtime
    5563              :         // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
    5564              :         // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
    5565              :         // simple coalescing mechanism.
    5566          118 :         let mut guard = tokio::select! {
    5567          118 :             guard = self.remote_tenant_manifest.lock() => guard,
    5568          118 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5569              :         };
    5570              : 
    5571              :         // Build a new manifest.
    5572          118 :         let manifest = self.build_tenant_manifest();
    5573              : 
    5574              :         // Check if the manifest has changed. We ignore the version number here, to avoid
    5575              :         // uploading every manifest on version number bumps.
    5576          118 :         if let Some(old) = guard.as_ref() {
    5577            4 :             if manifest.eq_ignoring_version(old) {
    5578            3 :                 return Ok(());
    5579            1 :             }
    5580          114 :         }
    5581              : 
    5582              :         // Update metrics
    5583          115 :         let tid = self.tenant_shard_id.to_string();
    5584          115 :         let shard_id = self.tenant_shard_id.shard_slug().to_string();
    5585          115 :         let set_key = &[tid.as_str(), shard_id.as_str()][..];
    5586          115 :         TENANT_OFFLOADED_TIMELINES
    5587          115 :             .with_label_values(set_key)
    5588          115 :             .set(manifest.offloaded_timelines.len() as u64);
    5589          115 : 
    5590          115 :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5591          115 :         match backoff::retry(
    5592          115 :             || async {
    5593          115 :                 upload_tenant_manifest(
    5594          115 :                     &self.remote_storage,
    5595          115 :                     &self.tenant_shard_id,
    5596          115 :                     self.generation,
    5597          115 :                     &manifest,
    5598          115 :                     &self.cancel,
    5599          115 :                 )
    5600          115 :                 .await
    5601          230 :             },
    5602          115 :             |_| self.cancel.is_cancelled(),
    5603          115 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5604          115 :             FAILED_REMOTE_OP_RETRIES,
    5605          115 :             "uploading tenant manifest",
    5606          115 :             &self.cancel,
    5607          115 :         )
    5608          115 :         .await
    5609              :         {
    5610            0 :             None => Err(TenantManifestError::Cancelled),
    5611            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5612            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5613              :             Some(Ok(_)) => {
    5614              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5615              :                 // re-uploading the same thing.
    5616          115 :                 *guard = Some(manifest);
    5617          115 : 
    5618          115 :                 Ok(())
    5619              :             }
    5620              :         }
    5621          118 :     }
    5622              : }
    5623              : 
    5624              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5625              : /// to get bootstrap data for timeline initialization.
    5626            0 : async fn run_initdb(
    5627            0 :     conf: &'static PageServerConf,
    5628            0 :     initdb_target_dir: &Utf8Path,
    5629            0 :     pg_version: u32,
    5630            0 :     cancel: &CancellationToken,
    5631            0 : ) -> Result<(), InitdbError> {
    5632            0 :     let initdb_bin_path = conf
    5633            0 :         .pg_bin_dir(pg_version)
    5634            0 :         .map_err(InitdbError::Other)?
    5635            0 :         .join("initdb");
    5636            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5637            0 :     info!(
    5638            0 :         "running {} in {}, libdir: {}",
    5639              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5640              :     );
    5641              : 
    5642            0 :     let _permit = {
    5643            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5644            0 :         INIT_DB_SEMAPHORE.acquire().await
    5645              :     };
    5646              : 
    5647            0 :     CONCURRENT_INITDBS.inc();
    5648            0 :     scopeguard::defer! {
    5649            0 :         CONCURRENT_INITDBS.dec();
    5650            0 :     }
    5651            0 : 
    5652            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5653            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5654            0 :         superuser: &conf.superuser,
    5655            0 :         locale: &conf.locale,
    5656            0 :         initdb_bin: &initdb_bin_path,
    5657            0 :         pg_version,
    5658            0 :         library_search_path: &initdb_lib_dir,
    5659            0 :         pgdata: initdb_target_dir,
    5660            0 :     })
    5661            0 :     .await
    5662            0 :     .map_err(InitdbError::Inner);
    5663            0 : 
    5664            0 :     // This isn't true cancellation support, see above. Still return an error to
    5665            0 :     // excercise the cancellation code path.
    5666            0 :     if cancel.is_cancelled() {
    5667            0 :         return Err(InitdbError::Cancelled);
    5668            0 :     }
    5669            0 : 
    5670            0 :     res
    5671            0 : }
    5672              : 
    5673              : /// Dump contents of a layer file to stdout.
    5674            0 : pub async fn dump_layerfile_from_path(
    5675            0 :     path: &Utf8Path,
    5676            0 :     verbose: bool,
    5677            0 :     ctx: &RequestContext,
    5678            0 : ) -> anyhow::Result<()> {
    5679              :     use std::os::unix::fs::FileExt;
    5680              : 
    5681              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5682              :     // file.
    5683            0 :     let file = File::open(path)?;
    5684            0 :     let mut header_buf = [0u8; 2];
    5685            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5686              : 
    5687            0 :     match u16::from_be_bytes(header_buf) {
    5688              :         crate::IMAGE_FILE_MAGIC => {
    5689            0 :             ImageLayer::new_for_path(path, file)?
    5690            0 :                 .dump(verbose, ctx)
    5691            0 :                 .await?
    5692              :         }
    5693              :         crate::DELTA_FILE_MAGIC => {
    5694            0 :             DeltaLayer::new_for_path(path, file)?
    5695            0 :                 .dump(verbose, ctx)
    5696            0 :                 .await?
    5697              :         }
    5698            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5699              :     }
    5700              : 
    5701            0 :     Ok(())
    5702            0 : }
    5703              : 
    5704              : #[cfg(test)]
    5705              : pub(crate) mod harness {
    5706              :     use bytes::{Bytes, BytesMut};
    5707              :     use hex_literal::hex;
    5708              :     use once_cell::sync::OnceCell;
    5709              :     use pageserver_api::key::Key;
    5710              :     use pageserver_api::models::ShardParameters;
    5711              :     use pageserver_api::record::NeonWalRecord;
    5712              :     use pageserver_api::shard::ShardIndex;
    5713              :     use utils::id::TenantId;
    5714              :     use utils::logging;
    5715              : 
    5716              :     use super::*;
    5717              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5718              :     use crate::l0_flush::L0FlushConfig;
    5719              :     use crate::walredo::apply_neon;
    5720              : 
    5721              :     pub const TIMELINE_ID: TimelineId =
    5722              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5723              :     pub const NEW_TIMELINE_ID: TimelineId =
    5724              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5725              : 
    5726              :     /// Convenience function to create a page image with given string as the only content
    5727      2514391 :     pub fn test_img(s: &str) -> Bytes {
    5728      2514391 :         let mut buf = BytesMut::new();
    5729      2514391 :         buf.extend_from_slice(s.as_bytes());
    5730      2514391 :         buf.resize(64, 0);
    5731      2514391 : 
    5732      2514391 :         buf.freeze()
    5733      2514391 :     }
    5734              : 
    5735              :     pub struct TenantHarness {
    5736              :         pub conf: &'static PageServerConf,
    5737              :         pub tenant_conf: pageserver_api::models::TenantConfig,
    5738              :         pub tenant_shard_id: TenantShardId,
    5739              :         pub generation: Generation,
    5740              :         pub shard: ShardIndex,
    5741              :         pub remote_storage: GenericRemoteStorage,
    5742              :         pub remote_fs_dir: Utf8PathBuf,
    5743              :         pub deletion_queue: MockDeletionQueue,
    5744              :     }
    5745              : 
    5746              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5747              : 
    5748          129 :     pub(crate) fn setup_logging() {
    5749          129 :         LOG_HANDLE.get_or_init(|| {
    5750          123 :             logging::init(
    5751          123 :                 logging::LogFormat::Test,
    5752          123 :                 // enable it in case the tests exercise code paths that use
    5753          123 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5754          123 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5755          123 :                 logging::Output::Stdout,
    5756          123 :             )
    5757          123 :             .expect("Failed to init test logging");
    5758          129 :         });
    5759          129 :     }
    5760              : 
    5761              :     impl TenantHarness {
    5762          117 :         pub async fn create_custom(
    5763          117 :             test_name: &'static str,
    5764          117 :             tenant_conf: pageserver_api::models::TenantConfig,
    5765          117 :             tenant_id: TenantId,
    5766          117 :             shard_identity: ShardIdentity,
    5767          117 :             generation: Generation,
    5768          117 :         ) -> anyhow::Result<Self> {
    5769          117 :             setup_logging();
    5770          117 : 
    5771          117 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5772          117 :             let _ = fs::remove_dir_all(&repo_dir);
    5773          117 :             fs::create_dir_all(&repo_dir)?;
    5774              : 
    5775          117 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5776          117 :             // Make a static copy of the config. This can never be free'd, but that's
    5777          117 :             // OK in a test.
    5778          117 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5779          117 : 
    5780          117 :             let shard = shard_identity.shard_index();
    5781          117 :             let tenant_shard_id = TenantShardId {
    5782          117 :                 tenant_id,
    5783          117 :                 shard_number: shard.shard_number,
    5784          117 :                 shard_count: shard.shard_count,
    5785          117 :             };
    5786          117 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5787          117 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5788              : 
    5789              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5790          117 :             let remote_fs_dir = conf.workdir.join("localfs");
    5791          117 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5792          117 :             let config = RemoteStorageConfig {
    5793          117 :                 storage: RemoteStorageKind::LocalFs {
    5794          117 :                     local_path: remote_fs_dir.clone(),
    5795          117 :                 },
    5796          117 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5797          117 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5798          117 :             };
    5799          117 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5800          117 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5801          117 : 
    5802          117 :             Ok(Self {
    5803          117 :                 conf,
    5804          117 :                 tenant_conf,
    5805          117 :                 tenant_shard_id,
    5806          117 :                 generation,
    5807          117 :                 shard,
    5808          117 :                 remote_storage,
    5809          117 :                 remote_fs_dir,
    5810          117 :                 deletion_queue,
    5811          117 :             })
    5812          117 :         }
    5813              : 
    5814          110 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5815          110 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5816          110 :             // The tests perform them manually if needed.
    5817          110 :             let tenant_conf = pageserver_api::models::TenantConfig {
    5818          110 :                 gc_period: Some(Duration::ZERO),
    5819          110 :                 compaction_period: Some(Duration::ZERO),
    5820          110 :                 ..Default::default()
    5821          110 :             };
    5822          110 :             let tenant_id = TenantId::generate();
    5823          110 :             let shard = ShardIdentity::unsharded();
    5824          110 :             Self::create_custom(
    5825          110 :                 test_name,
    5826          110 :                 tenant_conf,
    5827          110 :                 tenant_id,
    5828          110 :                 shard,
    5829          110 :                 Generation::new(0xdeadbeef),
    5830          110 :             )
    5831          110 :             .await
    5832          110 :         }
    5833              : 
    5834           10 :         pub fn span(&self) -> tracing::Span {
    5835           10 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5836           10 :         }
    5837              : 
    5838          117 :         pub(crate) async fn load(&self) -> (Arc<TenantShard>, RequestContext) {
    5839          117 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    5840          117 :                 .with_scope_unit_test();
    5841          117 :             (
    5842          117 :                 self.do_try_load(&ctx)
    5843          117 :                     .await
    5844          117 :                     .expect("failed to load test tenant"),
    5845          117 :                 ctx,
    5846          117 :             )
    5847          117 :         }
    5848              : 
    5849              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5850              :         pub(crate) async fn do_try_load(
    5851              :             &self,
    5852              :             ctx: &RequestContext,
    5853              :         ) -> anyhow::Result<Arc<TenantShard>> {
    5854              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5855              : 
    5856              :             let (basebackup_requst_sender, _) = tokio::sync::mpsc::unbounded_channel();
    5857              : 
    5858              :             let tenant = Arc::new(TenantShard::new(
    5859              :                 TenantState::Attaching,
    5860              :                 self.conf,
    5861              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5862              :                     self.tenant_conf.clone(),
    5863              :                     self.generation,
    5864              :                     &ShardParameters::default(),
    5865              :                 ))
    5866              :                 .unwrap(),
    5867              :                 // This is a legacy/test code path: sharding isn't supported here.
    5868              :                 ShardIdentity::unsharded(),
    5869              :                 Some(walredo_mgr),
    5870              :                 self.tenant_shard_id,
    5871              :                 self.remote_storage.clone(),
    5872              :                 self.deletion_queue.new_client(),
    5873              :                 // TODO: ideally we should run all unit tests with both configs
    5874              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5875              :                 basebackup_requst_sender,
    5876              :             ));
    5877              : 
    5878              :             let preload = tenant
    5879              :                 .preload(&self.remote_storage, CancellationToken::new())
    5880              :                 .await?;
    5881              :             tenant.attach(Some(preload), ctx).await?;
    5882              : 
    5883              :             tenant.state.send_replace(TenantState::Active);
    5884              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5885              :                 timeline.set_state(TimelineState::Active);
    5886              :             }
    5887              :             Ok(tenant)
    5888              :         }
    5889              : 
    5890            1 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5891            1 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5892            1 :         }
    5893              :     }
    5894              : 
    5895              :     // Mock WAL redo manager that doesn't do much
    5896              :     pub(crate) struct TestRedoManager;
    5897              : 
    5898              :     impl TestRedoManager {
    5899              :         /// # Cancel-Safety
    5900              :         ///
    5901              :         /// This method is cancellation-safe.
    5902        26774 :         pub async fn request_redo(
    5903        26774 :             &self,
    5904        26774 :             key: Key,
    5905        26774 :             lsn: Lsn,
    5906        26774 :             base_img: Option<(Lsn, Bytes)>,
    5907        26774 :             records: Vec<(Lsn, NeonWalRecord)>,
    5908        26774 :             _pg_version: u32,
    5909        26774 :             _redo_attempt_type: RedoAttemptType,
    5910        26774 :         ) -> Result<Bytes, walredo::Error> {
    5911      1403510 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5912        26774 :             if records_neon {
    5913              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5914        26774 :                 let mut page = match (base_img, records.first()) {
    5915        13029 :                     (Some((_lsn, img)), _) => {
    5916        13029 :                         let mut page = BytesMut::new();
    5917        13029 :                         page.extend_from_slice(&img);
    5918        13029 :                         page
    5919              :                     }
    5920        13745 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5921              :                     _ => {
    5922            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5923              :                     }
    5924              :                 };
    5925              : 
    5926      1430283 :                 for (record_lsn, record) in records {
    5927      1403510 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5928              :                 }
    5929        26773 :                 Ok(page.freeze())
    5930              :             } else {
    5931              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5932            0 :                 let s = format!(
    5933            0 :                     "redo for {} to get to {}, with {} and {} records",
    5934            0 :                     key,
    5935            0 :                     lsn,
    5936            0 :                     if base_img.is_some() {
    5937            0 :                         "base image"
    5938              :                     } else {
    5939            0 :                         "no base image"
    5940              :                     },
    5941            0 :                     records.len()
    5942            0 :                 );
    5943            0 :                 println!("{s}");
    5944            0 : 
    5945            0 :                 Ok(test_img(&s))
    5946              :             }
    5947        26774 :         }
    5948              :     }
    5949              : }
    5950              : 
    5951              : #[cfg(test)]
    5952              : mod tests {
    5953              :     use std::collections::{BTreeMap, BTreeSet};
    5954              : 
    5955              :     use bytes::{Bytes, BytesMut};
    5956              :     use hex_literal::hex;
    5957              :     use itertools::Itertools;
    5958              :     #[cfg(feature = "testing")]
    5959              :     use models::CompactLsnRange;
    5960              :     use pageserver_api::key::{
    5961              :         AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX, repl_origin_key,
    5962              :     };
    5963              :     use pageserver_api::keyspace::KeySpace;
    5964              :     #[cfg(feature = "testing")]
    5965              :     use pageserver_api::keyspace::KeySpaceRandomAccum;
    5966              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5967              :     #[cfg(feature = "testing")]
    5968              :     use pageserver_api::record::NeonWalRecord;
    5969              :     use pageserver_api::value::Value;
    5970              :     use pageserver_compaction::helpers::overlaps_with;
    5971              :     #[cfg(feature = "testing")]
    5972              :     use rand::SeedableRng;
    5973              :     #[cfg(feature = "testing")]
    5974              :     use rand::rngs::StdRng;
    5975              :     use rand::{Rng, thread_rng};
    5976              :     #[cfg(feature = "testing")]
    5977              :     use std::ops::Range;
    5978              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5979              :     use tests::storage_layer::ValuesReconstructState;
    5980              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5981              :     #[cfg(feature = "testing")]
    5982              :     use timeline::GcInfo;
    5983              :     #[cfg(feature = "testing")]
    5984              :     use timeline::InMemoryLayerTestDesc;
    5985              :     #[cfg(feature = "testing")]
    5986              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5987              :     use timeline::{CompactOptions, DeltaLayerTestDesc, VersionedKeySpaceQuery};
    5988              :     use utils::id::TenantId;
    5989              : 
    5990              :     use super::*;
    5991              :     use crate::DEFAULT_PG_VERSION;
    5992              :     use crate::keyspace::KeySpaceAccum;
    5993              :     use crate::tenant::harness::*;
    5994              :     use crate::tenant::timeline::CompactFlags;
    5995              : 
    5996              :     static TEST_KEY: Lazy<Key> =
    5997            9 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5998              : 
    5999              :     #[cfg(feature = "testing")]
    6000              :     struct TestTimelineSpecification {
    6001              :         start_lsn: Lsn,
    6002              :         last_record_lsn: Lsn,
    6003              : 
    6004              :         in_memory_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6005              :         delta_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6006              :         image_layers_shape: Vec<(Range<Key>, Lsn)>,
    6007              : 
    6008              :         gap_chance: u8,
    6009              :         will_init_chance: u8,
    6010              :     }
    6011              : 
    6012              :     #[cfg(feature = "testing")]
    6013              :     struct Storage {
    6014              :         storage: HashMap<(Key, Lsn), Value>,
    6015              :         start_lsn: Lsn,
    6016              :     }
    6017              : 
    6018              :     #[cfg(feature = "testing")]
    6019              :     impl Storage {
    6020        32000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    6021              :             use bytes::BufMut;
    6022              : 
    6023        32000 :             let mut crnt_lsn = lsn;
    6024        32000 :             let mut got_base = false;
    6025        32000 : 
    6026        32000 :             let mut acc = Vec::new();
    6027              : 
    6028      2831871 :             while crnt_lsn >= self.start_lsn {
    6029      2831871 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6030      1421172 :                     acc.push(value.clone());
    6031              : 
    6032      1402881 :                     match value {
    6033      1402881 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6034      1402881 :                             if *will_init {
    6035        13709 :                                 got_base = true;
    6036        13709 :                                 break;
    6037      1389172 :                             }
    6038              :                         }
    6039              :                         Value::Image(_) => {
    6040        18291 :                             got_base = true;
    6041        18291 :                             break;
    6042              :                         }
    6043            0 :                         _ => unreachable!(),
    6044              :                     }
    6045      1410699 :                 }
    6046              : 
    6047      2799871 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6048              :             }
    6049              : 
    6050        32000 :             assert!(
    6051        32000 :                 got_base,
    6052            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6053              :             );
    6054              : 
    6055        32000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6056              : 
    6057        32000 :             let mut blob = BytesMut::new();
    6058      1421172 :             for value in acc.into_iter().rev() {
    6059      1402881 :                 match value {
    6060      1402881 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6061      1402881 :                         blob.extend_from_slice(append.as_bytes());
    6062      1402881 :                     }
    6063        18291 :                     Value::Image(img) => {
    6064        18291 :                         blob.put(img);
    6065        18291 :                     }
    6066            0 :                     _ => unreachable!(),
    6067              :                 }
    6068              :             }
    6069              : 
    6070        32000 :             blob.into()
    6071        32000 :         }
    6072              :     }
    6073              : 
    6074              :     #[cfg(feature = "testing")]
    6075              :     #[allow(clippy::too_many_arguments)]
    6076            1 :     async fn randomize_timeline(
    6077            1 :         tenant: &Arc<TenantShard>,
    6078            1 :         new_timeline_id: TimelineId,
    6079            1 :         pg_version: u32,
    6080            1 :         spec: TestTimelineSpecification,
    6081            1 :         random: &mut rand::rngs::StdRng,
    6082            1 :         ctx: &RequestContext,
    6083            1 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6084            1 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6085            1 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6086              : 
    6087            2 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6088            2 :             let mut lsn = lsn_range.start;
    6089          202 :             while lsn < lsn_range.end {
    6090          200 :                 let mut key = key_range.start;
    6091        21018 :                 while key < key_range.end {
    6092        20818 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6093        20818 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6094        20818 : 
    6095        20818 :                     if gap {
    6096         1018 :                         continue;
    6097        19800 :                     }
    6098              : 
    6099        19800 :                     let record = if will_init {
    6100          191 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6101              :                     } else {
    6102        19609 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6103              :                     };
    6104              : 
    6105        19800 :                     storage.insert((key, lsn), record);
    6106        19800 : 
    6107        19800 :                     key = key.next();
    6108              :                 }
    6109          200 :                 lsn = Lsn(lsn.0 + 1);
    6110              :             }
    6111              : 
    6112              :             // Stash some interesting LSN for future use
    6113            6 :             for offset in [0, 5, 100].iter() {
    6114            6 :                 if *offset == 0 {
    6115            2 :                     interesting_lsns.push(lsn_range.start);
    6116            2 :                 } else {
    6117            4 :                     let below = lsn_range.start.checked_sub(*offset);
    6118            4 :                     match below {
    6119            4 :                         Some(v) if v >= spec.start_lsn => {
    6120            4 :                             interesting_lsns.push(v);
    6121            4 :                         }
    6122            0 :                         _ => {}
    6123              :                     }
    6124              : 
    6125            4 :                     let above = Lsn(lsn_range.start.0 + offset);
    6126            4 :                     interesting_lsns.push(above);
    6127              :                 }
    6128              :             }
    6129              :         }
    6130              : 
    6131            3 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6132            3 :             let mut lsn = lsn_range.start;
    6133          315 :             while lsn < lsn_range.end {
    6134          312 :                 let mut key = key_range.start;
    6135        11112 :                 while key < key_range.end {
    6136        10800 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6137        10800 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6138        10800 : 
    6139        10800 :                     if gap {
    6140          504 :                         continue;
    6141        10296 :                     }
    6142              : 
    6143        10296 :                     let record = if will_init {
    6144          103 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6145              :                     } else {
    6146        10193 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6147              :                     };
    6148              : 
    6149        10296 :                     storage.insert((key, lsn), record);
    6150        10296 : 
    6151        10296 :                     key = key.next();
    6152              :                 }
    6153          312 :                 lsn = Lsn(lsn.0 + 1);
    6154              :             }
    6155              : 
    6156              :             // Stash some interesting LSN for future use
    6157            9 :             for offset in [0, 5, 100].iter() {
    6158            9 :                 if *offset == 0 {
    6159            3 :                     interesting_lsns.push(lsn_range.start);
    6160            3 :                 } else {
    6161            6 :                     let below = lsn_range.start.checked_sub(*offset);
    6162            6 :                     match below {
    6163            6 :                         Some(v) if v >= spec.start_lsn => {
    6164            3 :                             interesting_lsns.push(v);
    6165            3 :                         }
    6166            3 :                         _ => {}
    6167              :                     }
    6168              : 
    6169            6 :                     let above = Lsn(lsn_range.start.0 + offset);
    6170            6 :                     interesting_lsns.push(above);
    6171              :                 }
    6172              :             }
    6173              :         }
    6174              : 
    6175            3 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6176            3 :             let mut key = key_range.start;
    6177          142 :             while key < key_range.end {
    6178          139 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6179          139 :                 let record = Value::Image(blob.clone());
    6180          139 :                 storage.insert((key, *lsn), record);
    6181          139 : 
    6182          139 :                 key = key.next();
    6183          139 :             }
    6184              : 
    6185              :             // Stash some interesting LSN for future use
    6186            9 :             for offset in [0, 5, 100].iter() {
    6187            9 :                 if *offset == 0 {
    6188            3 :                     interesting_lsns.push(*lsn);
    6189            3 :                 } else {
    6190            6 :                     let below = lsn.checked_sub(*offset);
    6191            6 :                     match below {
    6192            6 :                         Some(v) if v >= spec.start_lsn => {
    6193            4 :                             interesting_lsns.push(v);
    6194            4 :                         }
    6195            2 :                         _ => {}
    6196              :                     }
    6197              : 
    6198            6 :                     let above = Lsn(lsn.0 + offset);
    6199            6 :                     interesting_lsns.push(above);
    6200              :                 }
    6201              :             }
    6202              :         }
    6203              : 
    6204            1 :         let in_memory_test_layers = {
    6205            1 :             let mut acc = Vec::new();
    6206              : 
    6207            2 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6208            2 :                 let mut data = Vec::new();
    6209            2 : 
    6210            2 :                 let mut lsn = lsn_range.start;
    6211          202 :                 while lsn < lsn_range.end {
    6212          200 :                     let mut key = key_range.start;
    6213        20000 :                     while key < key_range.end {
    6214        19800 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6215        19800 :                             data.push((key, lsn, record.clone()));
    6216        19800 :                         }
    6217              : 
    6218        19800 :                         key = key.next();
    6219              :                     }
    6220          200 :                     lsn = Lsn(lsn.0 + 1);
    6221              :                 }
    6222              : 
    6223            2 :                 acc.push(InMemoryLayerTestDesc {
    6224            2 :                     data,
    6225            2 :                     lsn_range: lsn_range.clone(),
    6226            2 :                     is_open: false,
    6227            2 :                 })
    6228              :             }
    6229              : 
    6230            1 :             acc
    6231              :         };
    6232              : 
    6233            1 :         let delta_test_layers = {
    6234            1 :             let mut acc = Vec::new();
    6235              : 
    6236            3 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6237            3 :                 let mut data = Vec::new();
    6238            3 : 
    6239            3 :                 let mut lsn = lsn_range.start;
    6240          315 :                 while lsn < lsn_range.end {
    6241          312 :                     let mut key = key_range.start;
    6242        10608 :                     while key < key_range.end {
    6243        10296 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6244        10296 :                             data.push((key, lsn, record.clone()));
    6245        10296 :                         }
    6246              : 
    6247        10296 :                         key = key.next();
    6248              :                     }
    6249          312 :                     lsn = Lsn(lsn.0 + 1);
    6250              :                 }
    6251              : 
    6252            3 :                 acc.push(DeltaLayerTestDesc {
    6253            3 :                     data,
    6254            3 :                     lsn_range: lsn_range.clone(),
    6255            3 :                     key_range: key_range.clone(),
    6256            3 :                 })
    6257              :             }
    6258              : 
    6259            1 :             acc
    6260              :         };
    6261              : 
    6262            1 :         let image_test_layers = {
    6263            1 :             let mut acc = Vec::new();
    6264              : 
    6265            3 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6266            3 :                 let mut data = Vec::new();
    6267            3 : 
    6268            3 :                 let mut key = key_range.start;
    6269          142 :                 while key < key_range.end {
    6270          139 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6271          139 :                         let blob = match record {
    6272          139 :                             Value::Image(blob) => blob.clone(),
    6273            0 :                             _ => unreachable!(),
    6274              :                         };
    6275              : 
    6276          139 :                         data.push((key, blob));
    6277            0 :                     }
    6278              : 
    6279          139 :                     key = key.next();
    6280              :                 }
    6281              : 
    6282            3 :                 acc.push((*lsn, data));
    6283              :             }
    6284              : 
    6285            1 :             acc
    6286              :         };
    6287              : 
    6288            1 :         let tline = tenant
    6289            1 :             .create_test_timeline_with_layers(
    6290            1 :                 new_timeline_id,
    6291            1 :                 spec.start_lsn,
    6292            1 :                 pg_version,
    6293            1 :                 ctx,
    6294            1 :                 in_memory_test_layers,
    6295            1 :                 delta_test_layers,
    6296            1 :                 image_test_layers,
    6297            1 :                 spec.last_record_lsn,
    6298            1 :             )
    6299            1 :             .await?;
    6300              : 
    6301            1 :         Ok((
    6302            1 :             tline,
    6303            1 :             Storage {
    6304            1 :                 storage,
    6305            1 :                 start_lsn: spec.start_lsn,
    6306            1 :             },
    6307            1 :             interesting_lsns,
    6308            1 :         ))
    6309            1 :     }
    6310              : 
    6311              :     #[tokio::test]
    6312            1 :     async fn test_basic() -> anyhow::Result<()> {
    6313            1 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6314            1 :         let tline = tenant
    6315            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6316            1 :             .await?;
    6317            1 : 
    6318            1 :         let mut writer = tline.writer().await;
    6319            1 :         writer
    6320            1 :             .put(
    6321            1 :                 *TEST_KEY,
    6322            1 :                 Lsn(0x10),
    6323            1 :                 &Value::Image(test_img("foo at 0x10")),
    6324            1 :                 &ctx,
    6325            1 :             )
    6326            1 :             .await?;
    6327            1 :         writer.finish_write(Lsn(0x10));
    6328            1 :         drop(writer);
    6329            1 : 
    6330            1 :         let mut writer = tline.writer().await;
    6331            1 :         writer
    6332            1 :             .put(
    6333            1 :                 *TEST_KEY,
    6334            1 :                 Lsn(0x20),
    6335            1 :                 &Value::Image(test_img("foo at 0x20")),
    6336            1 :                 &ctx,
    6337            1 :             )
    6338            1 :             .await?;
    6339            1 :         writer.finish_write(Lsn(0x20));
    6340            1 :         drop(writer);
    6341            1 : 
    6342            1 :         assert_eq!(
    6343            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6344            1 :             test_img("foo at 0x10")
    6345            1 :         );
    6346            1 :         assert_eq!(
    6347            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6348            1 :             test_img("foo at 0x10")
    6349            1 :         );
    6350            1 :         assert_eq!(
    6351            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6352            1 :             test_img("foo at 0x20")
    6353            1 :         );
    6354            1 : 
    6355            1 :         Ok(())
    6356            1 :     }
    6357              : 
    6358              :     #[tokio::test]
    6359            1 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6360            1 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6361            1 :             .await?
    6362            1 :             .load()
    6363            1 :             .await;
    6364            1 :         let _ = tenant
    6365            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6366            1 :             .await?;
    6367            1 : 
    6368            1 :         match tenant
    6369            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6370            1 :             .await
    6371            1 :         {
    6372            1 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6373            1 :             Err(e) => assert_eq!(
    6374            1 :                 e.to_string(),
    6375            1 :                 "timeline already exists with different parameters".to_string()
    6376            1 :             ),
    6377            1 :         }
    6378            1 : 
    6379            1 :         Ok(())
    6380            1 :     }
    6381              : 
    6382              :     /// Convenience function to create a page image with given string as the only content
    6383            5 :     pub fn test_value(s: &str) -> Value {
    6384            5 :         let mut buf = BytesMut::new();
    6385            5 :         buf.extend_from_slice(s.as_bytes());
    6386            5 :         Value::Image(buf.freeze())
    6387            5 :     }
    6388              : 
    6389              :     ///
    6390              :     /// Test branch creation
    6391              :     ///
    6392              :     #[tokio::test]
    6393            1 :     async fn test_branch() -> anyhow::Result<()> {
    6394            1 :         use std::str::from_utf8;
    6395            1 : 
    6396            1 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6397            1 :         let tline = tenant
    6398            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6399            1 :             .await?;
    6400            1 :         let mut writer = tline.writer().await;
    6401            1 : 
    6402            1 :         #[allow(non_snake_case)]
    6403            1 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6404            1 :         #[allow(non_snake_case)]
    6405            1 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6406            1 : 
    6407            1 :         // Insert a value on the timeline
    6408            1 :         writer
    6409            1 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6410            1 :             .await?;
    6411            1 :         writer
    6412            1 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6413            1 :             .await?;
    6414            1 :         writer.finish_write(Lsn(0x20));
    6415            1 : 
    6416            1 :         writer
    6417            1 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6418            1 :             .await?;
    6419            1 :         writer.finish_write(Lsn(0x30));
    6420            1 :         writer
    6421            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6422            1 :             .await?;
    6423            1 :         writer.finish_write(Lsn(0x40));
    6424            1 : 
    6425            1 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6426            1 : 
    6427            1 :         // Branch the history, modify relation differently on the new timeline
    6428            1 :         tenant
    6429            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6430            1 :             .await?;
    6431            1 :         let newtline = tenant
    6432            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6433            1 :             .expect("Should have a local timeline");
    6434            1 :         let mut new_writer = newtline.writer().await;
    6435            1 :         new_writer
    6436            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6437            1 :             .await?;
    6438            1 :         new_writer.finish_write(Lsn(0x40));
    6439            1 : 
    6440            1 :         // Check page contents on both branches
    6441            1 :         assert_eq!(
    6442            1 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6443            1 :             "foo at 0x40"
    6444            1 :         );
    6445            1 :         assert_eq!(
    6446            1 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6447            1 :             "bar at 0x40"
    6448            1 :         );
    6449            1 :         assert_eq!(
    6450            1 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6451            1 :             "foobar at 0x20"
    6452            1 :         );
    6453            1 : 
    6454            1 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6455            1 : 
    6456            1 :         Ok(())
    6457            1 :     }
    6458              : 
    6459           10 :     async fn make_some_layers(
    6460           10 :         tline: &Timeline,
    6461           10 :         start_lsn: Lsn,
    6462           10 :         ctx: &RequestContext,
    6463           10 :     ) -> anyhow::Result<()> {
    6464           10 :         let mut lsn = start_lsn;
    6465              :         {
    6466           10 :             let mut writer = tline.writer().await;
    6467              :             // Create a relation on the timeline
    6468           10 :             writer
    6469           10 :                 .put(
    6470           10 :                     *TEST_KEY,
    6471           10 :                     lsn,
    6472           10 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6473           10 :                     ctx,
    6474           10 :                 )
    6475           10 :                 .await?;
    6476           10 :             writer.finish_write(lsn);
    6477           10 :             lsn += 0x10;
    6478           10 :             writer
    6479           10 :                 .put(
    6480           10 :                     *TEST_KEY,
    6481           10 :                     lsn,
    6482           10 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6483           10 :                     ctx,
    6484           10 :                 )
    6485           10 :                 .await?;
    6486           10 :             writer.finish_write(lsn);
    6487           10 :             lsn += 0x10;
    6488           10 :         }
    6489           10 :         tline.freeze_and_flush().await?;
    6490              :         {
    6491           10 :             let mut writer = tline.writer().await;
    6492           10 :             writer
    6493           10 :                 .put(
    6494           10 :                     *TEST_KEY,
    6495           10 :                     lsn,
    6496           10 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6497           10 :                     ctx,
    6498           10 :                 )
    6499           10 :                 .await?;
    6500           10 :             writer.finish_write(lsn);
    6501           10 :             lsn += 0x10;
    6502           10 :             writer
    6503           10 :                 .put(
    6504           10 :                     *TEST_KEY,
    6505           10 :                     lsn,
    6506           10 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6507           10 :                     ctx,
    6508           10 :                 )
    6509           10 :                 .await?;
    6510           10 :             writer.finish_write(lsn);
    6511           10 :         }
    6512           10 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6513           10 :     }
    6514              : 
    6515              :     #[tokio::test(start_paused = true)]
    6516            1 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6517            1 :         let (tenant, ctx) =
    6518            1 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6519            1 :                 .await?
    6520            1 :                 .load()
    6521            1 :                 .await;
    6522            1 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6523            1 :         // initial transition into AttachedSingle.
    6524            1 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6525            1 :         tokio::time::resume();
    6526            1 :         let tline = tenant
    6527            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6528            1 :             .await?;
    6529            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6530            1 : 
    6531            1 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6532            1 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6533            1 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6534            1 :         // below should fail.
    6535            1 :         tenant
    6536            1 :             .gc_iteration(
    6537            1 :                 Some(TIMELINE_ID),
    6538            1 :                 0x10,
    6539            1 :                 Duration::ZERO,
    6540            1 :                 &CancellationToken::new(),
    6541            1 :                 &ctx,
    6542            1 :             )
    6543            1 :             .await?;
    6544            1 : 
    6545            1 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6546            1 :         match tenant
    6547            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6548            1 :             .await
    6549            1 :         {
    6550            1 :             Ok(_) => panic!("branching should have failed"),
    6551            1 :             Err(err) => {
    6552            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6553            1 :                     panic!("wrong error type")
    6554            1 :                 };
    6555            1 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6556            1 :                 assert!(
    6557            1 :                     err.source()
    6558            1 :                         .unwrap()
    6559            1 :                         .to_string()
    6560            1 :                         .contains("we might've already garbage collected needed data")
    6561            1 :                 )
    6562            1 :             }
    6563            1 :         }
    6564            1 : 
    6565            1 :         Ok(())
    6566            1 :     }
    6567              : 
    6568              :     #[tokio::test]
    6569            1 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6570            1 :         let (tenant, ctx) =
    6571            1 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6572            1 :                 .await?
    6573            1 :                 .load()
    6574            1 :                 .await;
    6575            1 : 
    6576            1 :         let tline = tenant
    6577            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6578            1 :             .await?;
    6579            1 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6580            1 :         match tenant
    6581            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6582            1 :             .await
    6583            1 :         {
    6584            1 :             Ok(_) => panic!("branching should have failed"),
    6585            1 :             Err(err) => {
    6586            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6587            1 :                     panic!("wrong error type");
    6588            1 :                 };
    6589            1 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6590            1 :                 assert!(
    6591            1 :                     &err.source()
    6592            1 :                         .unwrap()
    6593            1 :                         .to_string()
    6594            1 :                         .contains("is earlier than latest GC cutoff")
    6595            1 :                 );
    6596            1 :             }
    6597            1 :         }
    6598            1 : 
    6599            1 :         Ok(())
    6600            1 :     }
    6601              : 
    6602              :     /*
    6603              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6604              :     // remove the old value, we'd need to work a little harder
    6605              :     #[tokio::test]
    6606              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6607              :         let repo =
    6608              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6609              :             .load();
    6610              : 
    6611              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6612              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6613              : 
    6614              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6615              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6616              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6617              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6618              :             Ok(_) => panic!("request for page should have failed"),
    6619              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6620              :         }
    6621              :         Ok(())
    6622              :     }
    6623              :      */
    6624              : 
    6625              :     #[tokio::test]
    6626            1 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6627            1 :         let (tenant, ctx) =
    6628            1 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6629            1 :                 .await?
    6630            1 :                 .load()
    6631            1 :                 .await;
    6632            1 :         let tline = tenant
    6633            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6634            1 :             .await?;
    6635            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6636            1 : 
    6637            1 :         tenant
    6638            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6639            1 :             .await?;
    6640            1 :         let newtline = tenant
    6641            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6642            1 :             .expect("Should have a local timeline");
    6643            1 : 
    6644            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6645            1 : 
    6646            1 :         tline.set_broken("test".to_owned());
    6647            1 : 
    6648            1 :         tenant
    6649            1 :             .gc_iteration(
    6650            1 :                 Some(TIMELINE_ID),
    6651            1 :                 0x10,
    6652            1 :                 Duration::ZERO,
    6653            1 :                 &CancellationToken::new(),
    6654            1 :                 &ctx,
    6655            1 :             )
    6656            1 :             .await?;
    6657            1 : 
    6658            1 :         // The branchpoints should contain all timelines, even ones marked
    6659            1 :         // as Broken.
    6660            1 :         {
    6661            1 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6662            1 :             assert_eq!(branchpoints.len(), 1);
    6663            1 :             assert_eq!(
    6664            1 :                 branchpoints[0],
    6665            1 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6666            1 :             );
    6667            1 :         }
    6668            1 : 
    6669            1 :         // You can read the key from the child branch even though the parent is
    6670            1 :         // Broken, as long as you don't need to access data from the parent.
    6671            1 :         assert_eq!(
    6672            1 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6673            1 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6674            1 :         );
    6675            1 : 
    6676            1 :         // This needs to traverse to the parent, and fails.
    6677            1 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6678            1 :         assert!(
    6679            1 :             err.to_string().starts_with(&format!(
    6680            1 :                 "bad state on timeline {}: Broken",
    6681            1 :                 tline.timeline_id
    6682            1 :             )),
    6683            1 :             "{err}"
    6684            1 :         );
    6685            1 : 
    6686            1 :         Ok(())
    6687            1 :     }
    6688              : 
    6689              :     #[tokio::test]
    6690            1 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6691            1 :         let (tenant, ctx) =
    6692            1 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6693            1 :                 .await?
    6694            1 :                 .load()
    6695            1 :                 .await;
    6696            1 :         let tline = tenant
    6697            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6698            1 :             .await?;
    6699            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6700            1 : 
    6701            1 :         tenant
    6702            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6703            1 :             .await?;
    6704            1 :         let newtline = tenant
    6705            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6706            1 :             .expect("Should have a local timeline");
    6707            1 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6708            1 :         tenant
    6709            1 :             .gc_iteration(
    6710            1 :                 Some(TIMELINE_ID),
    6711            1 :                 0x10,
    6712            1 :                 Duration::ZERO,
    6713            1 :                 &CancellationToken::new(),
    6714            1 :                 &ctx,
    6715            1 :             )
    6716            1 :             .await?;
    6717            1 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6718            1 : 
    6719            1 :         Ok(())
    6720            1 :     }
    6721              :     #[tokio::test]
    6722            1 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6723            1 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6724            1 :             .await?
    6725            1 :             .load()
    6726            1 :             .await;
    6727            1 :         let tline = tenant
    6728            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6729            1 :             .await?;
    6730            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6731            1 : 
    6732            1 :         tenant
    6733            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6734            1 :             .await?;
    6735            1 :         let newtline = tenant
    6736            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6737            1 :             .expect("Should have a local timeline");
    6738            1 : 
    6739            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6740            1 : 
    6741            1 :         // run gc on parent
    6742            1 :         tenant
    6743            1 :             .gc_iteration(
    6744            1 :                 Some(TIMELINE_ID),
    6745            1 :                 0x10,
    6746            1 :                 Duration::ZERO,
    6747            1 :                 &CancellationToken::new(),
    6748            1 :                 &ctx,
    6749            1 :             )
    6750            1 :             .await?;
    6751            1 : 
    6752            1 :         // Check that the data is still accessible on the branch.
    6753            1 :         assert_eq!(
    6754            1 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6755            1 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6756            1 :         );
    6757            1 : 
    6758            1 :         Ok(())
    6759            1 :     }
    6760              : 
    6761              :     #[tokio::test]
    6762            1 :     async fn timeline_load() -> anyhow::Result<()> {
    6763            1 :         const TEST_NAME: &str = "timeline_load";
    6764            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6765            1 :         {
    6766            1 :             let (tenant, ctx) = harness.load().await;
    6767            1 :             let tline = tenant
    6768            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6769            1 :                 .await?;
    6770            1 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6771            1 :             // so that all uploads finish & we can call harness.load() below again
    6772            1 :             tenant
    6773            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6774            1 :                 .instrument(harness.span())
    6775            1 :                 .await
    6776            1 :                 .ok()
    6777            1 :                 .unwrap();
    6778            1 :         }
    6779            1 : 
    6780            1 :         let (tenant, _ctx) = harness.load().await;
    6781            1 :         tenant
    6782            1 :             .get_timeline(TIMELINE_ID, true)
    6783            1 :             .expect("cannot load timeline");
    6784            1 : 
    6785            1 :         Ok(())
    6786            1 :     }
    6787              : 
    6788              :     #[tokio::test]
    6789            1 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6790            1 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6791            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6792            1 :         // create two timelines
    6793            1 :         {
    6794            1 :             let (tenant, ctx) = harness.load().await;
    6795            1 :             let tline = tenant
    6796            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6797            1 :                 .await?;
    6798            1 : 
    6799            1 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6800            1 : 
    6801            1 :             let child_tline = tenant
    6802            1 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6803            1 :                 .await?;
    6804            1 :             child_tline.set_state(TimelineState::Active);
    6805            1 : 
    6806            1 :             let newtline = tenant
    6807            1 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6808            1 :                 .expect("Should have a local timeline");
    6809            1 : 
    6810            1 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6811            1 : 
    6812            1 :             // so that all uploads finish & we can call harness.load() below again
    6813            1 :             tenant
    6814            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6815            1 :                 .instrument(harness.span())
    6816            1 :                 .await
    6817            1 :                 .ok()
    6818            1 :                 .unwrap();
    6819            1 :         }
    6820            1 : 
    6821            1 :         // check that both of them are initially unloaded
    6822            1 :         let (tenant, _ctx) = harness.load().await;
    6823            1 : 
    6824            1 :         // check that both, child and ancestor are loaded
    6825            1 :         let _child_tline = tenant
    6826            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6827            1 :             .expect("cannot get child timeline loaded");
    6828            1 : 
    6829            1 :         let _ancestor_tline = tenant
    6830            1 :             .get_timeline(TIMELINE_ID, true)
    6831            1 :             .expect("cannot get ancestor timeline loaded");
    6832            1 : 
    6833            1 :         Ok(())
    6834            1 :     }
    6835              : 
    6836              :     #[tokio::test]
    6837            1 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6838            1 :         use storage_layer::AsLayerDesc;
    6839            1 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6840            1 :             .await?
    6841            1 :             .load()
    6842            1 :             .await;
    6843            1 :         let tline = tenant
    6844            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6845            1 :             .await?;
    6846            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6847            1 : 
    6848            1 :         let layer_map = tline.layers.read().await;
    6849            1 :         let level0_deltas = layer_map
    6850            1 :             .layer_map()?
    6851            1 :             .level0_deltas()
    6852            1 :             .iter()
    6853            2 :             .map(|desc| layer_map.get_from_desc(desc))
    6854            1 :             .collect::<Vec<_>>();
    6855            1 : 
    6856            1 :         assert!(!level0_deltas.is_empty());
    6857            1 : 
    6858            3 :         for delta in level0_deltas {
    6859            1 :             // Ensure we are dumping a delta layer here
    6860            2 :             assert!(delta.layer_desc().is_delta);
    6861            2 :             delta.dump(true, &ctx).await.unwrap();
    6862            1 :         }
    6863            1 : 
    6864            1 :         Ok(())
    6865            1 :     }
    6866              : 
    6867              :     #[tokio::test]
    6868            1 :     async fn test_images() -> anyhow::Result<()> {
    6869            1 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6870            1 :         let tline = tenant
    6871            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6872            1 :             .await?;
    6873            1 : 
    6874            1 :         let mut writer = tline.writer().await;
    6875            1 :         writer
    6876            1 :             .put(
    6877            1 :                 *TEST_KEY,
    6878            1 :                 Lsn(0x10),
    6879            1 :                 &Value::Image(test_img("foo at 0x10")),
    6880            1 :                 &ctx,
    6881            1 :             )
    6882            1 :             .await?;
    6883            1 :         writer.finish_write(Lsn(0x10));
    6884            1 :         drop(writer);
    6885            1 : 
    6886            1 :         tline.freeze_and_flush().await?;
    6887            1 :         tline
    6888            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6889            1 :             .await?;
    6890            1 : 
    6891            1 :         let mut writer = tline.writer().await;
    6892            1 :         writer
    6893            1 :             .put(
    6894            1 :                 *TEST_KEY,
    6895            1 :                 Lsn(0x20),
    6896            1 :                 &Value::Image(test_img("foo at 0x20")),
    6897            1 :                 &ctx,
    6898            1 :             )
    6899            1 :             .await?;
    6900            1 :         writer.finish_write(Lsn(0x20));
    6901            1 :         drop(writer);
    6902            1 : 
    6903            1 :         tline.freeze_and_flush().await?;
    6904            1 :         tline
    6905            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6906            1 :             .await?;
    6907            1 : 
    6908            1 :         let mut writer = tline.writer().await;
    6909            1 :         writer
    6910            1 :             .put(
    6911            1 :                 *TEST_KEY,
    6912            1 :                 Lsn(0x30),
    6913            1 :                 &Value::Image(test_img("foo at 0x30")),
    6914            1 :                 &ctx,
    6915            1 :             )
    6916            1 :             .await?;
    6917            1 :         writer.finish_write(Lsn(0x30));
    6918            1 :         drop(writer);
    6919            1 : 
    6920            1 :         tline.freeze_and_flush().await?;
    6921            1 :         tline
    6922            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6923            1 :             .await?;
    6924            1 : 
    6925            1 :         let mut writer = tline.writer().await;
    6926            1 :         writer
    6927            1 :             .put(
    6928            1 :                 *TEST_KEY,
    6929            1 :                 Lsn(0x40),
    6930            1 :                 &Value::Image(test_img("foo at 0x40")),
    6931            1 :                 &ctx,
    6932            1 :             )
    6933            1 :             .await?;
    6934            1 :         writer.finish_write(Lsn(0x40));
    6935            1 :         drop(writer);
    6936            1 : 
    6937            1 :         tline.freeze_and_flush().await?;
    6938            1 :         tline
    6939            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6940            1 :             .await?;
    6941            1 : 
    6942            1 :         assert_eq!(
    6943            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6944            1 :             test_img("foo at 0x10")
    6945            1 :         );
    6946            1 :         assert_eq!(
    6947            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6948            1 :             test_img("foo at 0x10")
    6949            1 :         );
    6950            1 :         assert_eq!(
    6951            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6952            1 :             test_img("foo at 0x20")
    6953            1 :         );
    6954            1 :         assert_eq!(
    6955            1 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6956            1 :             test_img("foo at 0x30")
    6957            1 :         );
    6958            1 :         assert_eq!(
    6959            1 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6960            1 :             test_img("foo at 0x40")
    6961            1 :         );
    6962            1 : 
    6963            1 :         Ok(())
    6964            1 :     }
    6965              : 
    6966            2 :     async fn bulk_insert_compact_gc(
    6967            2 :         tenant: &TenantShard,
    6968            2 :         timeline: &Arc<Timeline>,
    6969            2 :         ctx: &RequestContext,
    6970            2 :         lsn: Lsn,
    6971            2 :         repeat: usize,
    6972            2 :         key_count: usize,
    6973            2 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6974            2 :         let compact = true;
    6975            2 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6976            2 :     }
    6977              : 
    6978            4 :     async fn bulk_insert_maybe_compact_gc(
    6979            4 :         tenant: &TenantShard,
    6980            4 :         timeline: &Arc<Timeline>,
    6981            4 :         ctx: &RequestContext,
    6982            4 :         mut lsn: Lsn,
    6983            4 :         repeat: usize,
    6984            4 :         key_count: usize,
    6985            4 :         compact: bool,
    6986            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6987            4 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6988            4 : 
    6989            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6990            4 :         let mut blknum = 0;
    6991            4 : 
    6992            4 :         // Enforce that key range is monotonously increasing
    6993            4 :         let mut keyspace = KeySpaceAccum::new();
    6994            4 : 
    6995            4 :         let cancel = CancellationToken::new();
    6996            4 : 
    6997            4 :         for _ in 0..repeat {
    6998          200 :             for _ in 0..key_count {
    6999      2000000 :                 test_key.field6 = blknum;
    7000      2000000 :                 let mut writer = timeline.writer().await;
    7001      2000000 :                 writer
    7002      2000000 :                     .put(
    7003      2000000 :                         test_key,
    7004      2000000 :                         lsn,
    7005      2000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7006      2000000 :                         ctx,
    7007      2000000 :                     )
    7008      2000000 :                     .await?;
    7009      2000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    7010      2000000 :                 writer.finish_write(lsn);
    7011      2000000 :                 drop(writer);
    7012      2000000 : 
    7013      2000000 :                 keyspace.add_key(test_key);
    7014      2000000 : 
    7015      2000000 :                 lsn = Lsn(lsn.0 + 0x10);
    7016      2000000 :                 blknum += 1;
    7017              :             }
    7018              : 
    7019          200 :             timeline.freeze_and_flush().await?;
    7020          200 :             if compact {
    7021              :                 // this requires timeline to be &Arc<Timeline>
    7022          100 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    7023          100 :             }
    7024              : 
    7025              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    7026              :             // originally was.
    7027          200 :             let res = tenant
    7028          200 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7029          200 :                 .await?;
    7030              : 
    7031          200 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7032              :         }
    7033              : 
    7034            4 :         Ok(inserted)
    7035            4 :     }
    7036              : 
    7037              :     //
    7038              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7039              :     // Repeat 50 times.
    7040              :     //
    7041              :     #[tokio::test]
    7042            1 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7043            1 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7044            1 :         let (tenant, ctx) = harness.load().await;
    7045            1 :         let tline = tenant
    7046            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7047            1 :             .await?;
    7048            1 : 
    7049            1 :         let lsn = Lsn(0x10);
    7050            1 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7051            1 : 
    7052            1 :         Ok(())
    7053            1 :     }
    7054              : 
    7055              :     // Test the vectored get real implementation against a simple sequential implementation.
    7056              :     //
    7057              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    7058              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    7059              :     // grow to the right on the X axis.
    7060              :     //                       [Delta]
    7061              :     //                 [Delta]
    7062              :     //           [Delta]
    7063              :     //    [Delta]
    7064              :     // ------------ Image ---------------
    7065              :     //
    7066              :     // After layer generation we pick the ranges to query as follows:
    7067              :     // 1. The beginning of each delta layer
    7068              :     // 2. At the seam between two adjacent delta layers
    7069              :     //
    7070              :     // There's one major downside to this test: delta layers only contains images,
    7071              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    7072              :     #[tokio::test]
    7073            1 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7074            1 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7075            1 :         let (tenant, ctx) = harness.load().await;
    7076            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7077            1 :         let tline = tenant
    7078            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7079            1 :             .await?;
    7080            1 : 
    7081            1 :         let lsn = Lsn(0x10);
    7082            1 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7083            1 : 
    7084            1 :         let guard = tline.layers.read().await;
    7085            1 :         let lm = guard.layer_map()?;
    7086            1 : 
    7087            1 :         lm.dump(true, &ctx).await?;
    7088            1 : 
    7089            1 :         let mut reads = Vec::new();
    7090            1 :         let mut prev = None;
    7091            6 :         lm.iter_historic_layers().for_each(|desc| {
    7092            6 :             if !desc.is_delta() {
    7093            1 :                 prev = Some(desc.clone());
    7094            1 :                 return;
    7095            5 :             }
    7096            5 : 
    7097            5 :             let start = desc.key_range.start;
    7098            5 :             let end = desc
    7099            5 :                 .key_range
    7100            5 :                 .start
    7101            5 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    7102            5 :             reads.push(KeySpace {
    7103            5 :                 ranges: vec![start..end],
    7104            5 :             });
    7105            1 : 
    7106            5 :             if let Some(prev) = &prev {
    7107            5 :                 if !prev.is_delta() {
    7108            5 :                     return;
    7109            1 :                 }
    7110            0 : 
    7111            0 :                 let first_range = Key {
    7112            0 :                     field6: prev.key_range.end.field6 - 4,
    7113            0 :                     ..prev.key_range.end
    7114            0 :                 }..prev.key_range.end;
    7115            0 : 
    7116            0 :                 let second_range = desc.key_range.start..Key {
    7117            0 :                     field6: desc.key_range.start.field6 + 4,
    7118            0 :                     ..desc.key_range.start
    7119            0 :                 };
    7120            0 : 
    7121            0 :                 reads.push(KeySpace {
    7122            0 :                     ranges: vec![first_range, second_range],
    7123            0 :                 });
    7124            1 :             };
    7125            1 : 
    7126            1 :             prev = Some(desc.clone());
    7127            6 :         });
    7128            1 : 
    7129            1 :         drop(guard);
    7130            1 : 
    7131            1 :         // Pick a big LSN such that we query over all the changes.
    7132            1 :         let reads_lsn = Lsn(u64::MAX - 1);
    7133            1 : 
    7134            6 :         for read in reads {
    7135            5 :             info!("Doing vectored read on {:?}", read);
    7136            1 : 
    7137            5 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7138            1 : 
    7139            5 :             let vectored_res = tline
    7140            5 :                 .get_vectored_impl(
    7141            5 :                     query,
    7142            5 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7143            5 :                     &ctx,
    7144            5 :                 )
    7145            5 :                 .await;
    7146            1 : 
    7147            5 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7148            5 :             let mut expect_missing = false;
    7149            5 :             let mut key = read.start().unwrap();
    7150          165 :             while key != read.end().unwrap() {
    7151          160 :                 if let Some(lsns) = inserted.get(&key) {
    7152          160 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7153          160 :                     match expected_lsn {
    7154          160 :                         Some(lsn) => {
    7155          160 :                             expected_lsns.insert(key, *lsn);
    7156          160 :                         }
    7157            1 :                         None => {
    7158            1 :                             expect_missing = true;
    7159            0 :                             break;
    7160            1 :                         }
    7161            1 :                     }
    7162            1 :                 } else {
    7163            1 :                     expect_missing = true;
    7164            0 :                     break;
    7165            1 :                 }
    7166            1 : 
    7167          160 :                 key = key.next();
    7168            1 :             }
    7169            1 : 
    7170            5 :             if expect_missing {
    7171            1 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7172            1 :             } else {
    7173          160 :                 for (key, image) in vectored_res? {
    7174          160 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7175          160 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7176          160 :                     assert_eq!(image?, expected_image);
    7177            1 :                 }
    7178            1 :             }
    7179            1 :         }
    7180            1 : 
    7181            1 :         Ok(())
    7182            1 :     }
    7183              : 
    7184              :     #[tokio::test]
    7185            1 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7186            1 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7187            1 : 
    7188            1 :         let (tenant, ctx) = harness.load().await;
    7189            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7190            1 :         let (tline, ctx) = tenant
    7191            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7192            1 :             .await?;
    7193            1 :         let tline = tline.raw_timeline().unwrap();
    7194            1 : 
    7195            1 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7196            1 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7197            1 :         modification.set_lsn(Lsn(0x1008))?;
    7198            1 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7199            1 :         modification.commit(&ctx).await?;
    7200            1 : 
    7201            1 :         let child_timeline_id = TimelineId::generate();
    7202            1 :         tenant
    7203            1 :             .branch_timeline_test(
    7204            1 :                 tline,
    7205            1 :                 child_timeline_id,
    7206            1 :                 Some(tline.get_last_record_lsn()),
    7207            1 :                 &ctx,
    7208            1 :             )
    7209            1 :             .await?;
    7210            1 : 
    7211            1 :         let child_timeline = tenant
    7212            1 :             .get_timeline(child_timeline_id, true)
    7213            1 :             .expect("Should have the branched timeline");
    7214            1 : 
    7215            1 :         let aux_keyspace = KeySpace {
    7216            1 :             ranges: vec![NON_INHERITED_RANGE],
    7217            1 :         };
    7218            1 :         let read_lsn = child_timeline.get_last_record_lsn();
    7219            1 : 
    7220            1 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7221            1 : 
    7222            1 :         let vectored_res = child_timeline
    7223            1 :             .get_vectored_impl(
    7224            1 :                 query,
    7225            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7226            1 :                 &ctx,
    7227            1 :             )
    7228            1 :             .await;
    7229            1 : 
    7230            1 :         let images = vectored_res?;
    7231            1 :         assert!(images.is_empty());
    7232            1 :         Ok(())
    7233            1 :     }
    7234              : 
    7235              :     // Test that vectored get handles layer gaps correctly
    7236              :     // by advancing into the next ancestor timeline if required.
    7237              :     //
    7238              :     // The test generates timelines that look like the diagram below.
    7239              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    7240              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    7241              :     //
    7242              :     // ```
    7243              :     //-------------------------------+
    7244              :     //                          ...  |
    7245              :     //               [   L1   ]      |
    7246              :     //     [ / L1   ]                | Child Timeline
    7247              :     // ...                           |
    7248              :     // ------------------------------+
    7249              :     //     [ X L1   ]                | Parent Timeline
    7250              :     // ------------------------------+
    7251              :     // ```
    7252              :     #[tokio::test]
    7253            1 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7254            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7255            1 :             // Make compaction deterministic
    7256            1 :             gc_period: Some(Duration::ZERO),
    7257            1 :             compaction_period: Some(Duration::ZERO),
    7258            1 :             // Encourage creation of L1 layers
    7259            1 :             checkpoint_distance: Some(16 * 1024),
    7260            1 :             compaction_target_size: Some(8 * 1024),
    7261            1 :             ..Default::default()
    7262            1 :         };
    7263            1 : 
    7264            1 :         let harness = TenantHarness::create_custom(
    7265            1 :             "test_get_vectored_key_gap",
    7266            1 :             tenant_conf,
    7267            1 :             TenantId::generate(),
    7268            1 :             ShardIdentity::unsharded(),
    7269            1 :             Generation::new(0xdeadbeef),
    7270            1 :         )
    7271            1 :         .await?;
    7272            1 :         let (tenant, ctx) = harness.load().await;
    7273            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7274            1 : 
    7275            1 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7276            1 :         let gap_at_key = current_key.add(100);
    7277            1 :         let mut current_lsn = Lsn(0x10);
    7278            1 : 
    7279            1 :         const KEY_COUNT: usize = 10_000;
    7280            1 : 
    7281            1 :         let timeline_id = TimelineId::generate();
    7282            1 :         let current_timeline = tenant
    7283            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7284            1 :             .await?;
    7285            1 : 
    7286            1 :         current_lsn += 0x100;
    7287            1 : 
    7288            1 :         let mut writer = current_timeline.writer().await;
    7289            1 :         writer
    7290            1 :             .put(
    7291            1 :                 gap_at_key,
    7292            1 :                 current_lsn,
    7293            1 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    7294            1 :                 &ctx,
    7295            1 :             )
    7296            1 :             .await?;
    7297            1 :         writer.finish_write(current_lsn);
    7298            1 :         drop(writer);
    7299            1 : 
    7300            1 :         let mut latest_lsns = HashMap::new();
    7301            1 :         latest_lsns.insert(gap_at_key, current_lsn);
    7302            1 : 
    7303            1 :         current_timeline.freeze_and_flush().await?;
    7304            1 : 
    7305            1 :         let child_timeline_id = TimelineId::generate();
    7306            1 : 
    7307            1 :         tenant
    7308            1 :             .branch_timeline_test(
    7309            1 :                 &current_timeline,
    7310            1 :                 child_timeline_id,
    7311            1 :                 Some(current_lsn),
    7312            1 :                 &ctx,
    7313            1 :             )
    7314            1 :             .await?;
    7315            1 :         let child_timeline = tenant
    7316            1 :             .get_timeline(child_timeline_id, true)
    7317            1 :             .expect("Should have the branched timeline");
    7318            1 : 
    7319        10001 :         for i in 0..KEY_COUNT {
    7320        10000 :             if current_key == gap_at_key {
    7321            1 :                 current_key = current_key.next();
    7322            1 :                 continue;
    7323         9999 :             }
    7324         9999 : 
    7325         9999 :             current_lsn += 0x10;
    7326            1 : 
    7327         9999 :             let mut writer = child_timeline.writer().await;
    7328         9999 :             writer
    7329         9999 :                 .put(
    7330         9999 :                     current_key,
    7331         9999 :                     current_lsn,
    7332         9999 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    7333         9999 :                     &ctx,
    7334         9999 :                 )
    7335         9999 :                 .await?;
    7336         9999 :             writer.finish_write(current_lsn);
    7337         9999 :             drop(writer);
    7338         9999 : 
    7339         9999 :             latest_lsns.insert(current_key, current_lsn);
    7340         9999 :             current_key = current_key.next();
    7341         9999 : 
    7342         9999 :             // Flush every now and then to encourage layer file creation.
    7343         9999 :             if i % 500 == 0 {
    7344           20 :                 child_timeline.freeze_and_flush().await?;
    7345         9979 :             }
    7346            1 :         }
    7347            1 : 
    7348            1 :         child_timeline.freeze_and_flush().await?;
    7349            1 :         let mut flags = EnumSet::new();
    7350            1 :         flags.insert(CompactFlags::ForceRepartition);
    7351            1 :         child_timeline
    7352            1 :             .compact(&CancellationToken::new(), flags, &ctx)
    7353            1 :             .await?;
    7354            1 : 
    7355            1 :         let key_near_end = {
    7356            1 :             let mut tmp = current_key;
    7357            1 :             tmp.field6 -= 10;
    7358            1 :             tmp
    7359            1 :         };
    7360            1 : 
    7361            1 :         let key_near_gap = {
    7362            1 :             let mut tmp = gap_at_key;
    7363            1 :             tmp.field6 -= 10;
    7364            1 :             tmp
    7365            1 :         };
    7366            1 : 
    7367            1 :         let read = KeySpace {
    7368            1 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7369            1 :         };
    7370            1 : 
    7371            1 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7372            1 : 
    7373            1 :         let results = child_timeline
    7374            1 :             .get_vectored_impl(
    7375            1 :                 query,
    7376            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7377            1 :                 &ctx,
    7378            1 :             )
    7379            1 :             .await?;
    7380            1 : 
    7381           22 :         for (key, img_res) in results {
    7382           21 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7383           21 :             assert_eq!(img_res?, expected);
    7384            1 :         }
    7385            1 : 
    7386            1 :         Ok(())
    7387            1 :     }
    7388              : 
    7389              :     // Test that vectored get descends into ancestor timelines correctly and
    7390              :     // does not return an image that's newer than requested.
    7391              :     //
    7392              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7393              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7394              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7395              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7396              :     // order to avoid returning an image that's too new. The test below constructs such
    7397              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7398              :     // ```
    7399              :     //    LSN
    7400              :     //     ^
    7401              :     //     |
    7402              :     //     |
    7403              :     // 500 | --------------------------------------> branch point
    7404              :     // 400 |        X
    7405              :     // 300 |        X
    7406              :     // 200 | --------------------------------------> requested lsn
    7407              :     // 100 |        X
    7408              :     //     |---------------------------------------> Key
    7409              :     //              |
    7410              :     //              ------> requested key
    7411              :     //
    7412              :     // Legend:
    7413              :     // * X - page images
    7414              :     // ```
    7415              :     #[tokio::test]
    7416            1 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7417            1 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7418            1 :         let (tenant, ctx) = harness.load().await;
    7419            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7420            1 : 
    7421            1 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7422            1 :         let end_key = start_key.add(1000);
    7423            1 :         let child_gap_at_key = start_key.add(500);
    7424            1 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7425            1 : 
    7426            1 :         let mut current_lsn = Lsn(0x10);
    7427            1 : 
    7428            1 :         let timeline_id = TimelineId::generate();
    7429            1 :         let parent_timeline = tenant
    7430            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7431            1 :             .await?;
    7432            1 : 
    7433            1 :         current_lsn += 0x100;
    7434            1 : 
    7435            4 :         for _ in 0..3 {
    7436            3 :             let mut key = start_key;
    7437         3003 :             while key < end_key {
    7438         3000 :                 current_lsn += 0x10;
    7439         3000 : 
    7440         3000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    7441            1 : 
    7442         3000 :                 let mut writer = parent_timeline.writer().await;
    7443         3000 :                 writer
    7444         3000 :                     .put(
    7445         3000 :                         key,
    7446         3000 :                         current_lsn,
    7447         3000 :                         &Value::Image(test_img(&image_value)),
    7448         3000 :                         &ctx,
    7449         3000 :                     )
    7450         3000 :                     .await?;
    7451         3000 :                 writer.finish_write(current_lsn);
    7452         3000 : 
    7453         3000 :                 if key == child_gap_at_key {
    7454            3 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7455         2997 :                 }
    7456            1 : 
    7457         3000 :                 key = key.next();
    7458            1 :             }
    7459            1 : 
    7460            3 :             parent_timeline.freeze_and_flush().await?;
    7461            1 :         }
    7462            1 : 
    7463            1 :         let child_timeline_id = TimelineId::generate();
    7464            1 : 
    7465            1 :         let child_timeline = tenant
    7466            1 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7467            1 :             .await?;
    7468            1 : 
    7469            1 :         let mut key = start_key;
    7470         1001 :         while key < end_key {
    7471         1000 :             if key == child_gap_at_key {
    7472            1 :                 key = key.next();
    7473            1 :                 continue;
    7474          999 :             }
    7475          999 : 
    7476          999 :             current_lsn += 0x10;
    7477            1 : 
    7478          999 :             let mut writer = child_timeline.writer().await;
    7479          999 :             writer
    7480          999 :                 .put(
    7481          999 :                     key,
    7482          999 :                     current_lsn,
    7483          999 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    7484          999 :                     &ctx,
    7485          999 :                 )
    7486          999 :                 .await?;
    7487          999 :             writer.finish_write(current_lsn);
    7488          999 : 
    7489          999 :             key = key.next();
    7490            1 :         }
    7491            1 : 
    7492            1 :         child_timeline.freeze_and_flush().await?;
    7493            1 : 
    7494            1 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7495            1 :         let mut query_lsns = Vec::new();
    7496            3 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7497           18 :             for offset in lsn_offsets {
    7498           15 :                 query_lsns.push(Lsn(image_lsn
    7499           15 :                     .0
    7500           15 :                     .checked_add_signed(offset)
    7501           15 :                     .expect("Shouldn't overflow")));
    7502           15 :             }
    7503            1 :         }
    7504            1 : 
    7505           16 :         for query_lsn in query_lsns {
    7506           15 :             let query = VersionedKeySpaceQuery::uniform(
    7507           15 :                 KeySpace {
    7508           15 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7509           15 :                 },
    7510           15 :                 query_lsn,
    7511           15 :             );
    7512            1 : 
    7513           15 :             let results = child_timeline
    7514           15 :                 .get_vectored_impl(
    7515           15 :                     query,
    7516           15 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7517           15 :                     &ctx,
    7518           15 :                 )
    7519           15 :                 .await;
    7520            1 : 
    7521           15 :             let expected_item = parent_gap_lsns
    7522           15 :                 .iter()
    7523           15 :                 .rev()
    7524           34 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7525           15 : 
    7526           15 :             info!(
    7527            1 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7528            1 :                 query_lsn, expected_item
    7529            1 :             );
    7530            1 : 
    7531           15 :             match expected_item {
    7532           13 :                 Some((_, img_value)) => {
    7533           13 :                     let key_results = results.expect("No vectored get error expected");
    7534           13 :                     let key_result = &key_results[&child_gap_at_key];
    7535           13 :                     let returned_img = key_result
    7536           13 :                         .as_ref()
    7537           13 :                         .expect("No page reconstruct error expected");
    7538           13 : 
    7539           13 :                     info!(
    7540            1 :                         "Vectored read at LSN {} returned image {}",
    7541            0 :                         query_lsn,
    7542            0 :                         std::str::from_utf8(returned_img)?
    7543            1 :                     );
    7544           13 :                     assert_eq!(*returned_img, test_img(img_value));
    7545            1 :                 }
    7546            1 :                 None => {
    7547            2 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7548            1 :                 }
    7549            1 :             }
    7550            1 :         }
    7551            1 : 
    7552            1 :         Ok(())
    7553            1 :     }
    7554              : 
    7555              :     #[tokio::test]
    7556            1 :     async fn test_random_updates() -> anyhow::Result<()> {
    7557            1 :         let names_algorithms = [
    7558            1 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7559            1 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7560            1 :         ];
    7561            3 :         for (name, algorithm) in names_algorithms {
    7562            2 :             test_random_updates_algorithm(name, algorithm).await?;
    7563            1 :         }
    7564            1 :         Ok(())
    7565            1 :     }
    7566              : 
    7567            2 :     async fn test_random_updates_algorithm(
    7568            2 :         name: &'static str,
    7569            2 :         compaction_algorithm: CompactionAlgorithm,
    7570            2 :     ) -> anyhow::Result<()> {
    7571            2 :         let mut harness = TenantHarness::create(name).await?;
    7572            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7573            2 :             kind: compaction_algorithm,
    7574            2 :         });
    7575            2 :         let (tenant, ctx) = harness.load().await;
    7576            2 :         let tline = tenant
    7577            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7578            2 :             .await?;
    7579              : 
    7580              :         const NUM_KEYS: usize = 1000;
    7581            2 :         let cancel = CancellationToken::new();
    7582            2 : 
    7583            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7584            2 :         let mut test_key_end = test_key;
    7585            2 :         test_key_end.field6 = NUM_KEYS as u32;
    7586            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7587            2 : 
    7588            2 :         let mut keyspace = KeySpaceAccum::new();
    7589            2 : 
    7590            2 :         // Track when each page was last modified. Used to assert that
    7591            2 :         // a read sees the latest page version.
    7592            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7593            2 : 
    7594            2 :         let mut lsn = Lsn(0x10);
    7595              :         #[allow(clippy::needless_range_loop)]
    7596         2002 :         for blknum in 0..NUM_KEYS {
    7597         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7598         2000 :             test_key.field6 = blknum as u32;
    7599         2000 :             let mut writer = tline.writer().await;
    7600         2000 :             writer
    7601         2000 :                 .put(
    7602         2000 :                     test_key,
    7603         2000 :                     lsn,
    7604         2000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7605         2000 :                     &ctx,
    7606         2000 :                 )
    7607         2000 :                 .await?;
    7608         2000 :             writer.finish_write(lsn);
    7609         2000 :             updated[blknum] = lsn;
    7610         2000 :             drop(writer);
    7611         2000 : 
    7612         2000 :             keyspace.add_key(test_key);
    7613              :         }
    7614              : 
    7615          102 :         for _ in 0..50 {
    7616       100100 :             for _ in 0..NUM_KEYS {
    7617       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7618       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7619       100000 :                 test_key.field6 = blknum as u32;
    7620       100000 :                 let mut writer = tline.writer().await;
    7621       100000 :                 writer
    7622       100000 :                     .put(
    7623       100000 :                         test_key,
    7624       100000 :                         lsn,
    7625       100000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7626       100000 :                         &ctx,
    7627       100000 :                     )
    7628       100000 :                     .await?;
    7629       100000 :                 writer.finish_write(lsn);
    7630       100000 :                 drop(writer);
    7631       100000 :                 updated[blknum] = lsn;
    7632              :             }
    7633              : 
    7634              :             // Read all the blocks
    7635       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7636       100000 :                 test_key.field6 = blknum as u32;
    7637       100000 :                 assert_eq!(
    7638       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7639       100000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7640              :                 );
    7641              :             }
    7642              : 
    7643              :             // Perform a cycle of flush, and GC
    7644          100 :             tline.freeze_and_flush().await?;
    7645          100 :             tenant
    7646          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7647          100 :                 .await?;
    7648              :         }
    7649              : 
    7650            2 :         Ok(())
    7651            2 :     }
    7652              : 
    7653              :     #[tokio::test]
    7654            1 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7655            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7656            1 :             .await?
    7657            1 :             .load()
    7658            1 :             .await;
    7659            1 :         let mut tline = tenant
    7660            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7661            1 :             .await?;
    7662            1 : 
    7663            1 :         const NUM_KEYS: usize = 1000;
    7664            1 : 
    7665            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7666            1 : 
    7667            1 :         let mut keyspace = KeySpaceAccum::new();
    7668            1 : 
    7669            1 :         let cancel = CancellationToken::new();
    7670            1 : 
    7671            1 :         // Track when each page was last modified. Used to assert that
    7672            1 :         // a read sees the latest page version.
    7673            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    7674            1 : 
    7675            1 :         let mut lsn = Lsn(0x10);
    7676            1 :         #[allow(clippy::needless_range_loop)]
    7677         1001 :         for blknum in 0..NUM_KEYS {
    7678         1000 :             lsn = Lsn(lsn.0 + 0x10);
    7679         1000 :             test_key.field6 = blknum as u32;
    7680         1000 :             let mut writer = tline.writer().await;
    7681         1000 :             writer
    7682         1000 :                 .put(
    7683         1000 :                     test_key,
    7684         1000 :                     lsn,
    7685         1000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7686         1000 :                     &ctx,
    7687         1000 :                 )
    7688         1000 :                 .await?;
    7689         1000 :             writer.finish_write(lsn);
    7690         1000 :             updated[blknum] = lsn;
    7691         1000 :             drop(writer);
    7692         1000 : 
    7693         1000 :             keyspace.add_key(test_key);
    7694            1 :         }
    7695            1 : 
    7696           51 :         for _ in 0..50 {
    7697           50 :             let new_tline_id = TimelineId::generate();
    7698           50 :             tenant
    7699           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7700           50 :                 .await?;
    7701           50 :             tline = tenant
    7702           50 :                 .get_timeline(new_tline_id, true)
    7703           50 :                 .expect("Should have the branched timeline");
    7704            1 : 
    7705        50050 :             for _ in 0..NUM_KEYS {
    7706        50000 :                 lsn = Lsn(lsn.0 + 0x10);
    7707        50000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7708        50000 :                 test_key.field6 = blknum as u32;
    7709        50000 :                 let mut writer = tline.writer().await;
    7710        50000 :                 writer
    7711        50000 :                     .put(
    7712        50000 :                         test_key,
    7713        50000 :                         lsn,
    7714        50000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7715        50000 :                         &ctx,
    7716        50000 :                     )
    7717        50000 :                     .await?;
    7718        50000 :                 println!("updating {} at {}", blknum, lsn);
    7719        50000 :                 writer.finish_write(lsn);
    7720        50000 :                 drop(writer);
    7721        50000 :                 updated[blknum] = lsn;
    7722            1 :             }
    7723            1 : 
    7724            1 :             // Read all the blocks
    7725        50000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7726        50000 :                 test_key.field6 = blknum as u32;
    7727        50000 :                 assert_eq!(
    7728        50000 :                     tline.get(test_key, lsn, &ctx).await?,
    7729        50000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7730            1 :                 );
    7731            1 :             }
    7732            1 : 
    7733            1 :             // Perform a cycle of flush, compact, and GC
    7734           50 :             tline.freeze_and_flush().await?;
    7735           50 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7736           50 :             tenant
    7737           50 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7738           50 :                 .await?;
    7739            1 :         }
    7740            1 : 
    7741            1 :         Ok(())
    7742            1 :     }
    7743              : 
    7744              :     #[tokio::test]
    7745            1 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7746            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7747            1 :             .await?
    7748            1 :             .load()
    7749            1 :             .await;
    7750            1 :         let mut tline = tenant
    7751            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7752            1 :             .await?;
    7753            1 : 
    7754            1 :         const NUM_KEYS: usize = 100;
    7755            1 :         const NUM_TLINES: usize = 50;
    7756            1 : 
    7757            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7758            1 :         // Track page mutation lsns across different timelines.
    7759            1 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7760            1 : 
    7761            1 :         let mut lsn = Lsn(0x10);
    7762            1 : 
    7763            1 :         #[allow(clippy::needless_range_loop)]
    7764           51 :         for idx in 0..NUM_TLINES {
    7765           50 :             let new_tline_id = TimelineId::generate();
    7766           50 :             tenant
    7767           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7768           50 :                 .await?;
    7769           50 :             tline = tenant
    7770           50 :                 .get_timeline(new_tline_id, true)
    7771           50 :                 .expect("Should have the branched timeline");
    7772            1 : 
    7773         5050 :             for _ in 0..NUM_KEYS {
    7774         5000 :                 lsn = Lsn(lsn.0 + 0x10);
    7775         5000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7776         5000 :                 test_key.field6 = blknum as u32;
    7777         5000 :                 let mut writer = tline.writer().await;
    7778         5000 :                 writer
    7779         5000 :                     .put(
    7780         5000 :                         test_key,
    7781         5000 :                         lsn,
    7782         5000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7783         5000 :                         &ctx,
    7784         5000 :                     )
    7785         5000 :                     .await?;
    7786         5000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7787         5000 :                 writer.finish_write(lsn);
    7788         5000 :                 drop(writer);
    7789         5000 :                 updated[idx][blknum] = lsn;
    7790            1 :             }
    7791            1 :         }
    7792            1 : 
    7793            1 :         // Read pages from leaf timeline across all ancestors.
    7794           50 :         for (idx, lsns) in updated.iter().enumerate() {
    7795         5000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7796            1 :                 // Skip empty mutations.
    7797         5000 :                 if lsn.0 == 0 {
    7798         1831 :                     continue;
    7799         3169 :                 }
    7800         3169 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7801         3169 :                 test_key.field6 = blknum as u32;
    7802         3169 :                 assert_eq!(
    7803         3169 :                     tline.get(test_key, *lsn, &ctx).await?,
    7804         3169 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7805            1 :                 );
    7806            1 :             }
    7807            1 :         }
    7808            1 :         Ok(())
    7809            1 :     }
    7810              : 
    7811              :     #[tokio::test]
    7812            1 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7813            1 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7814            1 :             .await?
    7815            1 :             .load()
    7816            1 :             .await;
    7817            1 : 
    7818            1 :         let initdb_lsn = Lsn(0x20);
    7819            1 :         let (utline, ctx) = tenant
    7820            1 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7821            1 :             .await?;
    7822            1 :         let tline = utline.raw_timeline().unwrap();
    7823            1 : 
    7824            1 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7825            1 :         tline.maybe_spawn_flush_loop();
    7826            1 : 
    7827            1 :         // Make sure the timeline has the minimum set of required keys for operation.
    7828            1 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7829            1 :         // Except if you `put` at `initdb_lsn`.
    7830            1 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7831            1 :         // It uses `repartition()`, which assumes some keys to be present.
    7832            1 :         // Let's make sure the test timeline can handle that case.
    7833            1 :         {
    7834            1 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7835            1 :             assert_eq!(
    7836            1 :                 timeline::FlushLoopState::Running {
    7837            1 :                     expect_initdb_optimization: false,
    7838            1 :                     initdb_optimization_count: 0,
    7839            1 :                 },
    7840            1 :                 *state
    7841            1 :             );
    7842            1 :             *state = timeline::FlushLoopState::Running {
    7843            1 :                 expect_initdb_optimization: true,
    7844            1 :                 initdb_optimization_count: 0,
    7845            1 :             };
    7846            1 :         }
    7847            1 : 
    7848            1 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7849            1 :         // As explained above, the optimization requires some keys to be present.
    7850            1 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7851            1 :         // This is what `create_test_timeline` does, by the way.
    7852            1 :         let mut modification = tline.begin_modification(initdb_lsn);
    7853            1 :         modification
    7854            1 :             .init_empty_test_timeline()
    7855            1 :             .context("init_empty_test_timeline")?;
    7856            1 :         modification
    7857            1 :             .commit(&ctx)
    7858            1 :             .await
    7859            1 :             .context("commit init_empty_test_timeline modification")?;
    7860            1 : 
    7861            1 :         // Do the flush. The flush code will check the expectations that we set above.
    7862            1 :         tline.freeze_and_flush().await?;
    7863            1 : 
    7864            1 :         // assert freeze_and_flush exercised the initdb optimization
    7865            1 :         {
    7866            1 :             let state = tline.flush_loop_state.lock().unwrap();
    7867            1 :             let timeline::FlushLoopState::Running {
    7868            1 :                 expect_initdb_optimization,
    7869            1 :                 initdb_optimization_count,
    7870            1 :             } = *state
    7871            1 :             else {
    7872            1 :                 panic!("unexpected state: {:?}", *state);
    7873            1 :             };
    7874            1 :             assert!(expect_initdb_optimization);
    7875            1 :             assert!(initdb_optimization_count > 0);
    7876            1 :         }
    7877            1 :         Ok(())
    7878            1 :     }
    7879              : 
    7880              :     #[tokio::test]
    7881            1 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7882            1 :         let name = "test_create_guard_crash";
    7883            1 :         let harness = TenantHarness::create(name).await?;
    7884            1 :         {
    7885            1 :             let (tenant, ctx) = harness.load().await;
    7886            1 :             let (tline, _ctx) = tenant
    7887            1 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7888            1 :                 .await?;
    7889            1 :             // Leave the timeline ID in [`TenantShard::timelines_creating`] to exclude attempting to create it again
    7890            1 :             let raw_tline = tline.raw_timeline().unwrap();
    7891            1 :             raw_tline
    7892            1 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7893            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))
    7894            1 :                 .await;
    7895            1 :             std::mem::forget(tline);
    7896            1 :         }
    7897            1 : 
    7898            1 :         let (tenant, _) = harness.load().await;
    7899            1 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7900            1 :             Ok(_) => panic!("timeline should've been removed during load"),
    7901            1 :             Err(e) => {
    7902            1 :                 assert_eq!(
    7903            1 :                     e,
    7904            1 :                     GetTimelineError::NotFound {
    7905            1 :                         tenant_id: tenant.tenant_shard_id,
    7906            1 :                         timeline_id: TIMELINE_ID,
    7907            1 :                     }
    7908            1 :                 )
    7909            1 :             }
    7910            1 :         }
    7911            1 : 
    7912            1 :         assert!(
    7913            1 :             !harness
    7914            1 :                 .conf
    7915            1 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7916            1 :                 .exists()
    7917            1 :         );
    7918            1 : 
    7919            1 :         Ok(())
    7920            1 :     }
    7921              : 
    7922              :     #[tokio::test]
    7923            1 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7924            1 :         let names_algorithms = [
    7925            1 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7926            1 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7927            1 :         ];
    7928            3 :         for (name, algorithm) in names_algorithms {
    7929            2 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7930            1 :         }
    7931            1 :         Ok(())
    7932            1 :     }
    7933              : 
    7934            2 :     async fn test_read_at_max_lsn_algorithm(
    7935            2 :         name: &'static str,
    7936            2 :         compaction_algorithm: CompactionAlgorithm,
    7937            2 :     ) -> anyhow::Result<()> {
    7938            2 :         let mut harness = TenantHarness::create(name).await?;
    7939            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7940            2 :             kind: compaction_algorithm,
    7941            2 :         });
    7942            2 :         let (tenant, ctx) = harness.load().await;
    7943            2 :         let tline = tenant
    7944            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7945            2 :             .await?;
    7946              : 
    7947            2 :         let lsn = Lsn(0x10);
    7948            2 :         let compact = false;
    7949            2 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7950              : 
    7951            2 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7952            2 :         let read_lsn = Lsn(u64::MAX - 1);
    7953              : 
    7954            2 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7955            2 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7956              : 
    7957            2 :         Ok(())
    7958            2 :     }
    7959              : 
    7960              :     #[tokio::test]
    7961            1 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7962            1 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7963            1 :         let (tenant, ctx) = harness.load().await;
    7964            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7965            1 :         let tline = tenant
    7966            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7967            1 :             .await?;
    7968            1 : 
    7969            1 :         const NUM_KEYS: usize = 1000;
    7970            1 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7971            1 : 
    7972            1 :         let cancel = CancellationToken::new();
    7973            1 : 
    7974            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7975            1 :         base_key.field1 = AUX_KEY_PREFIX;
    7976            1 :         let mut test_key = base_key;
    7977            1 : 
    7978            1 :         // Track when each page was last modified. Used to assert that
    7979            1 :         // a read sees the latest page version.
    7980            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    7981            1 : 
    7982            1 :         let mut lsn = Lsn(0x10);
    7983            1 :         #[allow(clippy::needless_range_loop)]
    7984         1001 :         for blknum in 0..NUM_KEYS {
    7985         1000 :             lsn = Lsn(lsn.0 + 0x10);
    7986         1000 :             test_key.field6 = (blknum * STEP) as u32;
    7987         1000 :             let mut writer = tline.writer().await;
    7988         1000 :             writer
    7989         1000 :                 .put(
    7990         1000 :                     test_key,
    7991         1000 :                     lsn,
    7992         1000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7993         1000 :                     &ctx,
    7994         1000 :                 )
    7995         1000 :                 .await?;
    7996         1000 :             writer.finish_write(lsn);
    7997         1000 :             updated[blknum] = lsn;
    7998         1000 :             drop(writer);
    7999            1 :         }
    8000            1 : 
    8001            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8002            1 : 
    8003           12 :         for iter in 0..=10 {
    8004            1 :             // Read all the blocks
    8005        11000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    8006        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8007        11000 :                 assert_eq!(
    8008        11000 :                     tline.get(test_key, lsn, &ctx).await?,
    8009        11000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    8010            1 :                 );
    8011            1 :             }
    8012            1 : 
    8013           11 :             let mut cnt = 0;
    8014           11 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8015            1 : 
    8016        11000 :             for (key, value) in tline
    8017           11 :                 .get_vectored_impl(
    8018           11 :                     query,
    8019           11 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    8020           11 :                     &ctx,
    8021           11 :                 )
    8022           11 :                 .await?
    8023            1 :             {
    8024        11000 :                 let blknum = key.field6 as usize;
    8025        11000 :                 let value = value?;
    8026        11000 :                 assert!(blknum % STEP == 0);
    8027        11000 :                 let blknum = blknum / STEP;
    8028        11000 :                 assert_eq!(
    8029        11000 :                     value,
    8030        11000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8031        11000 :                 );
    8032        11000 :                 cnt += 1;
    8033            1 :             }
    8034            1 : 
    8035           11 :             assert_eq!(cnt, NUM_KEYS);
    8036            1 : 
    8037        11011 :             for _ in 0..NUM_KEYS {
    8038        11000 :                 lsn = Lsn(lsn.0 + 0x10);
    8039        11000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8040        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8041        11000 :                 let mut writer = tline.writer().await;
    8042        11000 :                 writer
    8043        11000 :                     .put(
    8044        11000 :                         test_key,
    8045        11000 :                         lsn,
    8046        11000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8047        11000 :                         &ctx,
    8048        11000 :                     )
    8049        11000 :                     .await?;
    8050        11000 :                 writer.finish_write(lsn);
    8051        11000 :                 drop(writer);
    8052        11000 :                 updated[blknum] = lsn;
    8053            1 :             }
    8054            1 : 
    8055            1 :             // Perform two cycles of flush, compact, and GC
    8056           33 :             for round in 0..2 {
    8057           22 :                 tline.freeze_and_flush().await?;
    8058           22 :                 tline
    8059           22 :                     .compact(
    8060           22 :                         &cancel,
    8061           22 :                         if iter % 5 == 0 && round == 0 {
    8062            3 :                             let mut flags = EnumSet::new();
    8063            3 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8064            3 :                             flags.insert(CompactFlags::ForceRepartition);
    8065            3 :                             flags
    8066            1 :                         } else {
    8067           19 :                             EnumSet::empty()
    8068            1 :                         },
    8069           22 :                         &ctx,
    8070           22 :                     )
    8071           22 :                     .await?;
    8072           22 :                 tenant
    8073           22 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8074           22 :                     .await?;
    8075            1 :             }
    8076            1 :         }
    8077            1 : 
    8078            1 :         Ok(())
    8079            1 :     }
    8080              : 
    8081              :     #[tokio::test]
    8082            1 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8083            1 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8084            1 :         let (tenant, ctx) = harness.load().await;
    8085            1 :         let tline = tenant
    8086            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8087            1 :             .await?;
    8088            1 : 
    8089            1 :         let cancel = CancellationToken::new();
    8090            1 : 
    8091            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8092            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8093            1 :         let test_key = base_key;
    8094            1 :         let mut lsn = Lsn(0x10);
    8095            1 : 
    8096           21 :         for _ in 0..20 {
    8097           20 :             lsn = Lsn(lsn.0 + 0x10);
    8098           20 :             let mut writer = tline.writer().await;
    8099           20 :             writer
    8100           20 :                 .put(
    8101           20 :                     test_key,
    8102           20 :                     lsn,
    8103           20 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8104           20 :                     &ctx,
    8105           20 :                 )
    8106           20 :                 .await?;
    8107           20 :             writer.finish_write(lsn);
    8108           20 :             drop(writer);
    8109           20 :             tline.freeze_and_flush().await?; // force create a delta layer
    8110            1 :         }
    8111            1 : 
    8112            1 :         let before_num_l0_delta_files =
    8113            1 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    8114            1 : 
    8115            1 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8116            1 : 
    8117            1 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    8118            1 : 
    8119            1 :         assert!(
    8120            1 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8121            1 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8122            1 :         );
    8123            1 : 
    8124            1 :         assert_eq!(
    8125            1 :             tline.get(test_key, lsn, &ctx).await?,
    8126            1 :             test_img(&format!("{} at {}", 0, lsn))
    8127            1 :         );
    8128            1 : 
    8129            1 :         Ok(())
    8130            1 :     }
    8131              : 
    8132              :     #[tokio::test]
    8133            1 :     async fn test_aux_file_e2e() {
    8134            1 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8135            1 : 
    8136            1 :         let (tenant, ctx) = harness.load().await;
    8137            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8138            1 : 
    8139            1 :         let mut lsn = Lsn(0x08);
    8140            1 : 
    8141            1 :         let tline: Arc<Timeline> = tenant
    8142            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8143            1 :             .await
    8144            1 :             .unwrap();
    8145            1 : 
    8146            1 :         {
    8147            1 :             lsn += 8;
    8148            1 :             let mut modification = tline.begin_modification(lsn);
    8149            1 :             modification
    8150            1 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8151            1 :                 .await
    8152            1 :                 .unwrap();
    8153            1 :             modification.commit(&ctx).await.unwrap();
    8154            1 :         }
    8155            1 : 
    8156            1 :         // we can read everything from the storage
    8157            1 :         let files = tline
    8158            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8159            1 :             .await
    8160            1 :             .unwrap();
    8161            1 :         assert_eq!(
    8162            1 :             files.get("pg_logical/mappings/test1"),
    8163            1 :             Some(&bytes::Bytes::from_static(b"first"))
    8164            1 :         );
    8165            1 : 
    8166            1 :         {
    8167            1 :             lsn += 8;
    8168            1 :             let mut modification = tline.begin_modification(lsn);
    8169            1 :             modification
    8170            1 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8171            1 :                 .await
    8172            1 :                 .unwrap();
    8173            1 :             modification.commit(&ctx).await.unwrap();
    8174            1 :         }
    8175            1 : 
    8176            1 :         let files = tline
    8177            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8178            1 :             .await
    8179            1 :             .unwrap();
    8180            1 :         assert_eq!(
    8181            1 :             files.get("pg_logical/mappings/test2"),
    8182            1 :             Some(&bytes::Bytes::from_static(b"second"))
    8183            1 :         );
    8184            1 : 
    8185            1 :         let child = tenant
    8186            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8187            1 :             .await
    8188            1 :             .unwrap();
    8189            1 : 
    8190            1 :         let files = child
    8191            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8192            1 :             .await
    8193            1 :             .unwrap();
    8194            1 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8195            1 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8196            1 :     }
    8197              : 
    8198              :     #[tokio::test]
    8199            1 :     async fn test_repl_origin_tombstones() {
    8200            1 :         let harness = TenantHarness::create("test_repl_origin_tombstones")
    8201            1 :             .await
    8202            1 :             .unwrap();
    8203            1 : 
    8204            1 :         let (tenant, ctx) = harness.load().await;
    8205            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8206            1 : 
    8207            1 :         let mut lsn = Lsn(0x08);
    8208            1 : 
    8209            1 :         let tline: Arc<Timeline> = tenant
    8210            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8211            1 :             .await
    8212            1 :             .unwrap();
    8213            1 : 
    8214            1 :         let repl_lsn = Lsn(0x10);
    8215            1 :         {
    8216            1 :             lsn += 8;
    8217            1 :             let mut modification = tline.begin_modification(lsn);
    8218            1 :             modification.put_for_unit_test(repl_origin_key(2), Value::Image(Bytes::new()));
    8219            1 :             modification.set_replorigin(1, repl_lsn).await.unwrap();
    8220            1 :             modification.commit(&ctx).await.unwrap();
    8221            1 :         }
    8222            1 : 
    8223            1 :         // we can read everything from the storage
    8224            1 :         let repl_origins = tline
    8225            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8226            1 :             .await
    8227            1 :             .unwrap();
    8228            1 :         assert_eq!(repl_origins.len(), 1);
    8229            1 :         assert_eq!(repl_origins[&1], lsn);
    8230            1 : 
    8231            1 :         {
    8232            1 :             lsn += 8;
    8233            1 :             let mut modification = tline.begin_modification(lsn);
    8234            1 :             modification.put_for_unit_test(
    8235            1 :                 repl_origin_key(3),
    8236            1 :                 Value::Image(Bytes::copy_from_slice(b"cannot_decode_this")),
    8237            1 :             );
    8238            1 :             modification.commit(&ctx).await.unwrap();
    8239            1 :         }
    8240            1 :         let result = tline
    8241            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8242            1 :             .await;
    8243            1 :         assert!(result.is_err());
    8244            1 :     }
    8245              : 
    8246              :     #[tokio::test]
    8247            1 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8248            1 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8249            1 :         let (tenant, ctx) = harness.load().await;
    8250            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8251            1 :         let tline = tenant
    8252            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8253            1 :             .await?;
    8254            1 : 
    8255            1 :         const NUM_KEYS: usize = 1000;
    8256            1 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8257            1 : 
    8258            1 :         let cancel = CancellationToken::new();
    8259            1 : 
    8260            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8261            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8262            1 :         let mut test_key = base_key;
    8263            1 :         let mut lsn = Lsn(0x10);
    8264            1 : 
    8265            4 :         async fn scan_with_statistics(
    8266            4 :             tline: &Timeline,
    8267            4 :             keyspace: &KeySpace,
    8268            4 :             lsn: Lsn,
    8269            4 :             ctx: &RequestContext,
    8270            4 :             io_concurrency: IoConcurrency,
    8271            4 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8272            4 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8273            4 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8274            4 :             let res = tline
    8275            4 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8276            4 :                 .await?;
    8277            4 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8278            4 :         }
    8279            1 : 
    8280         1001 :         for blknum in 0..NUM_KEYS {
    8281         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8282         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8283         1000 :             let mut writer = tline.writer().await;
    8284         1000 :             writer
    8285         1000 :                 .put(
    8286         1000 :                     test_key,
    8287         1000 :                     lsn,
    8288         1000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8289         1000 :                     &ctx,
    8290         1000 :                 )
    8291         1000 :                 .await?;
    8292         1000 :             writer.finish_write(lsn);
    8293         1000 :             drop(writer);
    8294            1 :         }
    8295            1 : 
    8296            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8297            1 : 
    8298           11 :         for iter in 1..=10 {
    8299        10010 :             for _ in 0..NUM_KEYS {
    8300        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    8301        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8302        10000 :                 test_key.field6 = (blknum * STEP) as u32;
    8303        10000 :                 let mut writer = tline.writer().await;
    8304        10000 :                 writer
    8305        10000 :                     .put(
    8306        10000 :                         test_key,
    8307        10000 :                         lsn,
    8308        10000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8309        10000 :                         &ctx,
    8310        10000 :                     )
    8311        10000 :                     .await?;
    8312        10000 :                 writer.finish_write(lsn);
    8313        10000 :                 drop(writer);
    8314            1 :             }
    8315            1 : 
    8316           10 :             tline.freeze_and_flush().await?;
    8317            1 : 
    8318           10 :             if iter % 5 == 0 {
    8319            2 :                 let (_, before_delta_file_accessed) =
    8320            2 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    8321            2 :                         .await?;
    8322            2 :                 tline
    8323            2 :                     .compact(
    8324            2 :                         &cancel,
    8325            2 :                         {
    8326            2 :                             let mut flags = EnumSet::new();
    8327            2 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8328            2 :                             flags.insert(CompactFlags::ForceRepartition);
    8329            2 :                             flags
    8330            2 :                         },
    8331            2 :                         &ctx,
    8332            2 :                     )
    8333            2 :                     .await?;
    8334            2 :                 let (_, after_delta_file_accessed) =
    8335            2 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    8336            2 :                         .await?;
    8337            2 :                 assert!(
    8338            2 :                     after_delta_file_accessed < before_delta_file_accessed,
    8339            1 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8340            1 :                 );
    8341            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.
    8342            2 :                 assert!(
    8343            2 :                     after_delta_file_accessed <= 2,
    8344            1 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8345            1 :                 );
    8346            8 :             }
    8347            1 :         }
    8348            1 : 
    8349            1 :         Ok(())
    8350            1 :     }
    8351              : 
    8352              :     #[tokio::test]
    8353            1 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8354            1 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8355            1 :         let (tenant, ctx) = harness.load().await;
    8356            1 : 
    8357            1 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8358            1 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8359            1 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8360            1 : 
    8361            1 :         let tline = tenant
    8362            1 :             .create_test_timeline_with_layers(
    8363            1 :                 TIMELINE_ID,
    8364            1 :                 Lsn(0x10),
    8365            1 :                 DEFAULT_PG_VERSION,
    8366            1 :                 &ctx,
    8367            1 :                 Vec::new(), // in-memory layers
    8368            1 :                 Vec::new(), // delta layers
    8369            1 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8370            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
    8371            1 :             )
    8372            1 :             .await?;
    8373            1 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8374            1 : 
    8375            1 :         let child = tenant
    8376            1 :             .branch_timeline_test_with_layers(
    8377            1 :                 &tline,
    8378            1 :                 NEW_TIMELINE_ID,
    8379            1 :                 Some(Lsn(0x20)),
    8380            1 :                 &ctx,
    8381            1 :                 Vec::new(), // delta layers
    8382            1 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8383            1 :                 Lsn(0x30),
    8384            1 :             )
    8385            1 :             .await
    8386            1 :             .unwrap();
    8387            1 : 
    8388            1 :         let lsn = Lsn(0x30);
    8389            1 : 
    8390            1 :         // test vectored get on parent timeline
    8391            1 :         assert_eq!(
    8392            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8393            1 :             Some(test_img("data key 1"))
    8394            1 :         );
    8395            1 :         assert!(
    8396            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8397            1 :                 .await
    8398            1 :                 .unwrap_err()
    8399            1 :                 .is_missing_key_error()
    8400            1 :         );
    8401            1 :         assert!(
    8402            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8403            1 :                 .await
    8404            1 :                 .unwrap_err()
    8405            1 :                 .is_missing_key_error()
    8406            1 :         );
    8407            1 : 
    8408            1 :         // test vectored get on child timeline
    8409            1 :         assert_eq!(
    8410            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8411            1 :             Some(test_img("data key 1"))
    8412            1 :         );
    8413            1 :         assert_eq!(
    8414            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8415            1 :             Some(test_img("data key 2"))
    8416            1 :         );
    8417            1 :         assert!(
    8418            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8419            1 :                 .await
    8420            1 :                 .unwrap_err()
    8421            1 :                 .is_missing_key_error()
    8422            1 :         );
    8423            1 : 
    8424            1 :         Ok(())
    8425            1 :     }
    8426              : 
    8427              :     #[tokio::test]
    8428            1 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8429            1 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8430            1 :         let (tenant, ctx) = harness.load().await;
    8431            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8432            1 : 
    8433            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8434            1 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8435            1 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8436            1 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8437            1 : 
    8438            1 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8439            1 :         let base_inherited_key_child =
    8440            1 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8441            1 :         let base_inherited_key_nonexist =
    8442            1 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8443            1 :         let base_inherited_key_overwrite =
    8444            1 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8445            1 : 
    8446            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8447            1 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8448            1 : 
    8449            1 :         let tline = tenant
    8450            1 :             .create_test_timeline_with_layers(
    8451            1 :                 TIMELINE_ID,
    8452            1 :                 Lsn(0x10),
    8453            1 :                 DEFAULT_PG_VERSION,
    8454            1 :                 &ctx,
    8455            1 :                 Vec::new(), // in-memory layers
    8456            1 :                 Vec::new(), // delta layers
    8457            1 :                 vec![(
    8458            1 :                     Lsn(0x20),
    8459            1 :                     vec![
    8460            1 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8461            1 :                         (
    8462            1 :                             base_inherited_key_overwrite,
    8463            1 :                             test_img("metadata key overwrite 1a"),
    8464            1 :                         ),
    8465            1 :                         (base_key, test_img("metadata key 1")),
    8466            1 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8467            1 :                     ],
    8468            1 :                 )], // image layers
    8469            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
    8470            1 :             )
    8471            1 :             .await?;
    8472            1 : 
    8473            1 :         let child = tenant
    8474            1 :             .branch_timeline_test_with_layers(
    8475            1 :                 &tline,
    8476            1 :                 NEW_TIMELINE_ID,
    8477            1 :                 Some(Lsn(0x20)),
    8478            1 :                 &ctx,
    8479            1 :                 Vec::new(), // delta layers
    8480            1 :                 vec![(
    8481            1 :                     Lsn(0x30),
    8482            1 :                     vec![
    8483            1 :                         (
    8484            1 :                             base_inherited_key_child,
    8485            1 :                             test_img("metadata inherited key 2"),
    8486            1 :                         ),
    8487            1 :                         (
    8488            1 :                             base_inherited_key_overwrite,
    8489            1 :                             test_img("metadata key overwrite 2a"),
    8490            1 :                         ),
    8491            1 :                         (base_key_child, test_img("metadata key 2")),
    8492            1 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8493            1 :                     ],
    8494            1 :                 )], // image layers
    8495            1 :                 Lsn(0x30),
    8496            1 :             )
    8497            1 :             .await
    8498            1 :             .unwrap();
    8499            1 : 
    8500            1 :         let lsn = Lsn(0x30);
    8501            1 : 
    8502            1 :         // test vectored get on parent timeline
    8503            1 :         assert_eq!(
    8504            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8505            1 :             Some(test_img("metadata key 1"))
    8506            1 :         );
    8507            1 :         assert_eq!(
    8508            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8509            1 :             None
    8510            1 :         );
    8511            1 :         assert_eq!(
    8512            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8513            1 :             None
    8514            1 :         );
    8515            1 :         assert_eq!(
    8516            1 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8517            1 :             Some(test_img("metadata key overwrite 1b"))
    8518            1 :         );
    8519            1 :         assert_eq!(
    8520            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8521            1 :             Some(test_img("metadata inherited key 1"))
    8522            1 :         );
    8523            1 :         assert_eq!(
    8524            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8525            1 :             None
    8526            1 :         );
    8527            1 :         assert_eq!(
    8528            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8529            1 :             None
    8530            1 :         );
    8531            1 :         assert_eq!(
    8532            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8533            1 :             Some(test_img("metadata key overwrite 1a"))
    8534            1 :         );
    8535            1 : 
    8536            1 :         // test vectored get on child timeline
    8537            1 :         assert_eq!(
    8538            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8539            1 :             None
    8540            1 :         );
    8541            1 :         assert_eq!(
    8542            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8543            1 :             Some(test_img("metadata key 2"))
    8544            1 :         );
    8545            1 :         assert_eq!(
    8546            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8547            1 :             None
    8548            1 :         );
    8549            1 :         assert_eq!(
    8550            1 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8551            1 :             Some(test_img("metadata inherited key 1"))
    8552            1 :         );
    8553            1 :         assert_eq!(
    8554            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8555            1 :             Some(test_img("metadata inherited key 2"))
    8556            1 :         );
    8557            1 :         assert_eq!(
    8558            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8559            1 :             None
    8560            1 :         );
    8561            1 :         assert_eq!(
    8562            1 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8563            1 :             Some(test_img("metadata key overwrite 2b"))
    8564            1 :         );
    8565            1 :         assert_eq!(
    8566            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8567            1 :             Some(test_img("metadata key overwrite 2a"))
    8568            1 :         );
    8569            1 : 
    8570            1 :         // test vectored scan on parent timeline
    8571            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8572            1 :         let query =
    8573            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8574            1 :         let res = tline
    8575            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8576            1 :             .await?;
    8577            1 : 
    8578            1 :         assert_eq!(
    8579            1 :             res.into_iter()
    8580            4 :                 .map(|(k, v)| (k, v.unwrap()))
    8581            1 :                 .collect::<Vec<_>>(),
    8582            1 :             vec![
    8583            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8584            1 :                 (
    8585            1 :                     base_inherited_key_overwrite,
    8586            1 :                     test_img("metadata key overwrite 1a")
    8587            1 :                 ),
    8588            1 :                 (base_key, test_img("metadata key 1")),
    8589            1 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8590            1 :             ]
    8591            1 :         );
    8592            1 : 
    8593            1 :         // test vectored scan on child timeline
    8594            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8595            1 :         let query =
    8596            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8597            1 :         let res = child
    8598            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8599            1 :             .await?;
    8600            1 : 
    8601            1 :         assert_eq!(
    8602            1 :             res.into_iter()
    8603            5 :                 .map(|(k, v)| (k, v.unwrap()))
    8604            1 :                 .collect::<Vec<_>>(),
    8605            1 :             vec![
    8606            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8607            1 :                 (
    8608            1 :                     base_inherited_key_child,
    8609            1 :                     test_img("metadata inherited key 2")
    8610            1 :                 ),
    8611            1 :                 (
    8612            1 :                     base_inherited_key_overwrite,
    8613            1 :                     test_img("metadata key overwrite 2a")
    8614            1 :                 ),
    8615            1 :                 (base_key_child, test_img("metadata key 2")),
    8616            1 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8617            1 :             ]
    8618            1 :         );
    8619            1 : 
    8620            1 :         Ok(())
    8621            1 :     }
    8622              : 
    8623           28 :     async fn get_vectored_impl_wrapper(
    8624           28 :         tline: &Arc<Timeline>,
    8625           28 :         key: Key,
    8626           28 :         lsn: Lsn,
    8627           28 :         ctx: &RequestContext,
    8628           28 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8629           28 :         let io_concurrency = IoConcurrency::spawn_from_conf(
    8630           28 :             tline.conf.get_vectored_concurrent_io,
    8631           28 :             tline.gate.enter().unwrap(),
    8632           28 :         );
    8633           28 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8634           28 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8635           28 :         let mut res = tline
    8636           28 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8637           28 :             .await?;
    8638           25 :         Ok(res.pop_last().map(|(k, v)| {
    8639           16 :             assert_eq!(k, key);
    8640           16 :             v.unwrap()
    8641           25 :         }))
    8642           28 :     }
    8643              : 
    8644              :     #[tokio::test]
    8645            1 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8646            1 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8647            1 :         let (tenant, ctx) = harness.load().await;
    8648            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8649            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8650            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8651            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8652            1 : 
    8653            1 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8654            1 :         // Lsn 0x30 key0, key3, no key1+key2
    8655            1 :         // Lsn 0x20 key1+key2 tomestones
    8656            1 :         // Lsn 0x10 key1 in image, key2 in delta
    8657            1 :         let tline = tenant
    8658            1 :             .create_test_timeline_with_layers(
    8659            1 :                 TIMELINE_ID,
    8660            1 :                 Lsn(0x10),
    8661            1 :                 DEFAULT_PG_VERSION,
    8662            1 :                 &ctx,
    8663            1 :                 Vec::new(), // in-memory layers
    8664            1 :                 // delta layers
    8665            1 :                 vec![
    8666            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8667            1 :                         Lsn(0x10)..Lsn(0x20),
    8668            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8669            1 :                     ),
    8670            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8671            1 :                         Lsn(0x20)..Lsn(0x30),
    8672            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8673            1 :                     ),
    8674            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8675            1 :                         Lsn(0x20)..Lsn(0x30),
    8676            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8677            1 :                     ),
    8678            1 :                 ],
    8679            1 :                 // image layers
    8680            1 :                 vec![
    8681            1 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8682            1 :                     (
    8683            1 :                         Lsn(0x30),
    8684            1 :                         vec![
    8685            1 :                             (key0, test_img("metadata key 0")),
    8686            1 :                             (key3, test_img("metadata key 3")),
    8687            1 :                         ],
    8688            1 :                     ),
    8689            1 :                 ],
    8690            1 :                 Lsn(0x30),
    8691            1 :             )
    8692            1 :             .await?;
    8693            1 : 
    8694            1 :         let lsn = Lsn(0x30);
    8695            1 :         let old_lsn = Lsn(0x20);
    8696            1 : 
    8697            1 :         assert_eq!(
    8698            1 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8699            1 :             Some(test_img("metadata key 0"))
    8700            1 :         );
    8701            1 :         assert_eq!(
    8702            1 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8703            1 :             None,
    8704            1 :         );
    8705            1 :         assert_eq!(
    8706            1 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8707            1 :             None,
    8708            1 :         );
    8709            1 :         assert_eq!(
    8710            1 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8711            1 :             Some(Bytes::new()),
    8712            1 :         );
    8713            1 :         assert_eq!(
    8714            1 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8715            1 :             Some(Bytes::new()),
    8716            1 :         );
    8717            1 :         assert_eq!(
    8718            1 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8719            1 :             Some(test_img("metadata key 3"))
    8720            1 :         );
    8721            1 : 
    8722            1 :         Ok(())
    8723            1 :     }
    8724              : 
    8725              :     #[tokio::test]
    8726            1 :     async fn test_metadata_tombstone_image_creation() {
    8727            1 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8728            1 :             .await
    8729            1 :             .unwrap();
    8730            1 :         let (tenant, ctx) = harness.load().await;
    8731            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8732            1 : 
    8733            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8734            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8735            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8736            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8737            1 : 
    8738            1 :         let tline = tenant
    8739            1 :             .create_test_timeline_with_layers(
    8740            1 :                 TIMELINE_ID,
    8741            1 :                 Lsn(0x10),
    8742            1 :                 DEFAULT_PG_VERSION,
    8743            1 :                 &ctx,
    8744            1 :                 Vec::new(), // in-memory layers
    8745            1 :                 // delta layers
    8746            1 :                 vec![
    8747            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8748            1 :                         Lsn(0x10)..Lsn(0x20),
    8749            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8750            1 :                     ),
    8751            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8752            1 :                         Lsn(0x20)..Lsn(0x30),
    8753            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8754            1 :                     ),
    8755            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8756            1 :                         Lsn(0x20)..Lsn(0x30),
    8757            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8758            1 :                     ),
    8759            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8760            1 :                         Lsn(0x30)..Lsn(0x40),
    8761            1 :                         vec![
    8762            1 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8763            1 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8764            1 :                         ],
    8765            1 :                     ),
    8766            1 :                 ],
    8767            1 :                 // image layers
    8768            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8769            1 :                 Lsn(0x40),
    8770            1 :             )
    8771            1 :             .await
    8772            1 :             .unwrap();
    8773            1 : 
    8774            1 :         let cancel = CancellationToken::new();
    8775            1 : 
    8776            1 :         tline
    8777            1 :             .compact(
    8778            1 :                 &cancel,
    8779            1 :                 {
    8780            1 :                     let mut flags = EnumSet::new();
    8781            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8782            1 :                     flags.insert(CompactFlags::ForceRepartition);
    8783            1 :                     flags
    8784            1 :                 },
    8785            1 :                 &ctx,
    8786            1 :             )
    8787            1 :             .await
    8788            1 :             .unwrap();
    8789            1 : 
    8790            1 :         // Image layers are created at last_record_lsn
    8791            1 :         let images = tline
    8792            1 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8793            1 :             .await
    8794            1 :             .unwrap()
    8795            1 :             .into_iter()
    8796            9 :             .filter(|(k, _)| k.is_metadata_key())
    8797            1 :             .collect::<Vec<_>>();
    8798            1 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8799            1 :     }
    8800              : 
    8801              :     #[tokio::test]
    8802            1 :     async fn test_metadata_tombstone_empty_image_creation() {
    8803            1 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8804            1 :             .await
    8805            1 :             .unwrap();
    8806            1 :         let (tenant, ctx) = harness.load().await;
    8807            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8808            1 : 
    8809            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8810            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8811            1 : 
    8812            1 :         let tline = tenant
    8813            1 :             .create_test_timeline_with_layers(
    8814            1 :                 TIMELINE_ID,
    8815            1 :                 Lsn(0x10),
    8816            1 :                 DEFAULT_PG_VERSION,
    8817            1 :                 &ctx,
    8818            1 :                 Vec::new(), // in-memory layers
    8819            1 :                 // delta layers
    8820            1 :                 vec![
    8821            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8822            1 :                         Lsn(0x10)..Lsn(0x20),
    8823            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8824            1 :                     ),
    8825            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8826            1 :                         Lsn(0x20)..Lsn(0x30),
    8827            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8828            1 :                     ),
    8829            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8830            1 :                         Lsn(0x20)..Lsn(0x30),
    8831            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8832            1 :                     ),
    8833            1 :                 ],
    8834            1 :                 // image layers
    8835            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8836            1 :                 Lsn(0x30),
    8837            1 :             )
    8838            1 :             .await
    8839            1 :             .unwrap();
    8840            1 : 
    8841            1 :         let cancel = CancellationToken::new();
    8842            1 : 
    8843            1 :         tline
    8844            1 :             .compact(
    8845            1 :                 &cancel,
    8846            1 :                 {
    8847            1 :                     let mut flags = EnumSet::new();
    8848            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8849            1 :                     flags.insert(CompactFlags::ForceRepartition);
    8850            1 :                     flags
    8851            1 :                 },
    8852            1 :                 &ctx,
    8853            1 :             )
    8854            1 :             .await
    8855            1 :             .unwrap();
    8856            1 : 
    8857            1 :         // Image layers are created at last_record_lsn
    8858            1 :         let images = tline
    8859            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8860            1 :             .await
    8861            1 :             .unwrap()
    8862            1 :             .into_iter()
    8863            7 :             .filter(|(k, _)| k.is_metadata_key())
    8864            1 :             .collect::<Vec<_>>();
    8865            1 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8866            1 :     }
    8867              : 
    8868              :     #[tokio::test]
    8869            1 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8870            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8871            1 :         let (tenant, ctx) = harness.load().await;
    8872            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8873            1 : 
    8874           51 :         fn get_key(id: u32) -> Key {
    8875           51 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8876           51 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8877           51 :             key.field6 = id;
    8878           51 :             key
    8879           51 :         }
    8880            1 : 
    8881            1 :         // We create
    8882            1 :         // - one bottom-most image layer,
    8883            1 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8884            1 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8885            1 :         // - a delta layer D3 above the horizon.
    8886            1 :         //
    8887            1 :         //                             | D3 |
    8888            1 :         //  | D1 |
    8889            1 :         // -|    |-- gc horizon -----------------
    8890            1 :         //  |    |                | D2 |
    8891            1 :         // --------- img layer ------------------
    8892            1 :         //
    8893            1 :         // What we should expact from this compaction is:
    8894            1 :         //                             | D3 |
    8895            1 :         //  | Part of D1 |
    8896            1 :         // --------- img layer with D1+D2 at GC horizon------------------
    8897            1 : 
    8898            1 :         // img layer at 0x10
    8899            1 :         let img_layer = (0..10)
    8900           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8901            1 :             .collect_vec();
    8902            1 : 
    8903            1 :         let delta1 = vec![
    8904            1 :             (
    8905            1 :                 get_key(1),
    8906            1 :                 Lsn(0x20),
    8907            1 :                 Value::Image(Bytes::from("value 1@0x20")),
    8908            1 :             ),
    8909            1 :             (
    8910            1 :                 get_key(2),
    8911            1 :                 Lsn(0x30),
    8912            1 :                 Value::Image(Bytes::from("value 2@0x30")),
    8913            1 :             ),
    8914            1 :             (
    8915            1 :                 get_key(3),
    8916            1 :                 Lsn(0x40),
    8917            1 :                 Value::Image(Bytes::from("value 3@0x40")),
    8918            1 :             ),
    8919            1 :         ];
    8920            1 :         let delta2 = vec![
    8921            1 :             (
    8922            1 :                 get_key(5),
    8923            1 :                 Lsn(0x20),
    8924            1 :                 Value::Image(Bytes::from("value 5@0x20")),
    8925            1 :             ),
    8926            1 :             (
    8927            1 :                 get_key(6),
    8928            1 :                 Lsn(0x20),
    8929            1 :                 Value::Image(Bytes::from("value 6@0x20")),
    8930            1 :             ),
    8931            1 :         ];
    8932            1 :         let delta3 = vec![
    8933            1 :             (
    8934            1 :                 get_key(8),
    8935            1 :                 Lsn(0x48),
    8936            1 :                 Value::Image(Bytes::from("value 8@0x48")),
    8937            1 :             ),
    8938            1 :             (
    8939            1 :                 get_key(9),
    8940            1 :                 Lsn(0x48),
    8941            1 :                 Value::Image(Bytes::from("value 9@0x48")),
    8942            1 :             ),
    8943            1 :         ];
    8944            1 : 
    8945            1 :         let tline = tenant
    8946            1 :             .create_test_timeline_with_layers(
    8947            1 :                 TIMELINE_ID,
    8948            1 :                 Lsn(0x10),
    8949            1 :                 DEFAULT_PG_VERSION,
    8950            1 :                 &ctx,
    8951            1 :                 Vec::new(), // in-memory layers
    8952            1 :                 vec![
    8953            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8954            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8955            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8956            1 :                 ], // delta layers
    8957            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8958            1 :                 Lsn(0x50),
    8959            1 :             )
    8960            1 :             .await?;
    8961            1 :         {
    8962            1 :             tline
    8963            1 :                 .applied_gc_cutoff_lsn
    8964            1 :                 .lock_for_write()
    8965            1 :                 .store_and_unlock(Lsn(0x30))
    8966            1 :                 .wait()
    8967            1 :                 .await;
    8968            1 :             // Update GC info
    8969            1 :             let mut guard = tline.gc_info.write().unwrap();
    8970            1 :             guard.cutoffs.time = Some(Lsn(0x30));
    8971            1 :             guard.cutoffs.space = Lsn(0x30);
    8972            1 :         }
    8973            1 : 
    8974            1 :         let expected_result = [
    8975            1 :             Bytes::from_static(b"value 0@0x10"),
    8976            1 :             Bytes::from_static(b"value 1@0x20"),
    8977            1 :             Bytes::from_static(b"value 2@0x30"),
    8978            1 :             Bytes::from_static(b"value 3@0x40"),
    8979            1 :             Bytes::from_static(b"value 4@0x10"),
    8980            1 :             Bytes::from_static(b"value 5@0x20"),
    8981            1 :             Bytes::from_static(b"value 6@0x20"),
    8982            1 :             Bytes::from_static(b"value 7@0x10"),
    8983            1 :             Bytes::from_static(b"value 8@0x48"),
    8984            1 :             Bytes::from_static(b"value 9@0x48"),
    8985            1 :         ];
    8986            1 : 
    8987           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    8988           10 :             assert_eq!(
    8989           10 :                 tline
    8990           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8991           10 :                     .await
    8992           10 :                     .unwrap(),
    8993            1 :                 expected
    8994            1 :             );
    8995            1 :         }
    8996            1 : 
    8997            1 :         let cancel = CancellationToken::new();
    8998            1 :         tline
    8999            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9000            1 :             .await
    9001            1 :             .unwrap();
    9002            1 : 
    9003           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9004           10 :             assert_eq!(
    9005           10 :                 tline
    9006           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9007           10 :                     .await
    9008           10 :                     .unwrap(),
    9009            1 :                 expected
    9010            1 :             );
    9011            1 :         }
    9012            1 : 
    9013            1 :         // Check if the image layer at the GC horizon contains exactly what we want
    9014            1 :         let image_at_gc_horizon = tline
    9015            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9016            1 :             .await
    9017            1 :             .unwrap()
    9018            1 :             .into_iter()
    9019           17 :             .filter(|(k, _)| k.is_metadata_key())
    9020            1 :             .collect::<Vec<_>>();
    9021            1 : 
    9022            1 :         assert_eq!(image_at_gc_horizon.len(), 10);
    9023            1 :         let expected_result = [
    9024            1 :             Bytes::from_static(b"value 0@0x10"),
    9025            1 :             Bytes::from_static(b"value 1@0x20"),
    9026            1 :             Bytes::from_static(b"value 2@0x30"),
    9027            1 :             Bytes::from_static(b"value 3@0x10"),
    9028            1 :             Bytes::from_static(b"value 4@0x10"),
    9029            1 :             Bytes::from_static(b"value 5@0x20"),
    9030            1 :             Bytes::from_static(b"value 6@0x20"),
    9031            1 :             Bytes::from_static(b"value 7@0x10"),
    9032            1 :             Bytes::from_static(b"value 8@0x10"),
    9033            1 :             Bytes::from_static(b"value 9@0x10"),
    9034            1 :         ];
    9035           11 :         for idx in 0..10 {
    9036           10 :             assert_eq!(
    9037           10 :                 image_at_gc_horizon[idx],
    9038           10 :                 (get_key(idx as u32), expected_result[idx].clone())
    9039           10 :             );
    9040            1 :         }
    9041            1 : 
    9042            1 :         // Check if old layers are removed / new layers have the expected LSN
    9043            1 :         let all_layers = inspect_and_sort(&tline, None).await;
    9044            1 :         assert_eq!(
    9045            1 :             all_layers,
    9046            1 :             vec![
    9047            1 :                 // Image layer at GC horizon
    9048            1 :                 PersistentLayerKey {
    9049            1 :                     key_range: Key::MIN..Key::MAX,
    9050            1 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    9051            1 :                     is_delta: false
    9052            1 :                 },
    9053            1 :                 // The delta layer below the horizon
    9054            1 :                 PersistentLayerKey {
    9055            1 :                     key_range: get_key(3)..get_key(4),
    9056            1 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    9057            1 :                     is_delta: true
    9058            1 :                 },
    9059            1 :                 // The delta3 layer that should not be picked for the compaction
    9060            1 :                 PersistentLayerKey {
    9061            1 :                     key_range: get_key(8)..get_key(10),
    9062            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9063            1 :                     is_delta: true
    9064            1 :                 }
    9065            1 :             ]
    9066            1 :         );
    9067            1 : 
    9068            1 :         // increase GC horizon and compact again
    9069            1 :         {
    9070            1 :             tline
    9071            1 :                 .applied_gc_cutoff_lsn
    9072            1 :                 .lock_for_write()
    9073            1 :                 .store_and_unlock(Lsn(0x40))
    9074            1 :                 .wait()
    9075            1 :                 .await;
    9076            1 :             // Update GC info
    9077            1 :             let mut guard = tline.gc_info.write().unwrap();
    9078            1 :             guard.cutoffs.time = Some(Lsn(0x40));
    9079            1 :             guard.cutoffs.space = Lsn(0x40);
    9080            1 :         }
    9081            1 :         tline
    9082            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9083            1 :             .await
    9084            1 :             .unwrap();
    9085            1 : 
    9086            1 :         Ok(())
    9087            1 :     }
    9088              : 
    9089              :     #[cfg(feature = "testing")]
    9090              :     #[tokio::test]
    9091            1 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9092            1 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9093            1 :         let (tenant, ctx) = harness.load().await;
    9094            1 : 
    9095           17 :         fn get_key(id: u32) -> Key {
    9096           17 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9097           17 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9098           17 :             key.field6 = id;
    9099           17 :             key
    9100           17 :         }
    9101            1 : 
    9102            1 :         let delta1 = vec![
    9103            1 :             (
    9104            1 :                 get_key(1),
    9105            1 :                 Lsn(0x20),
    9106            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9107            1 :             ),
    9108            1 :             (
    9109            1 :                 get_key(1),
    9110            1 :                 Lsn(0x30),
    9111            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9112            1 :             ),
    9113            1 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9114            1 :             (
    9115            1 :                 get_key(2),
    9116            1 :                 Lsn(0x20),
    9117            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9118            1 :             ),
    9119            1 :             (
    9120            1 :                 get_key(2),
    9121            1 :                 Lsn(0x30),
    9122            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9123            1 :             ),
    9124            1 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9125            1 :             (
    9126            1 :                 get_key(3),
    9127            1 :                 Lsn(0x20),
    9128            1 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9129            1 :             ),
    9130            1 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9131            1 :             (
    9132            1 :                 get_key(4),
    9133            1 :                 Lsn(0x20),
    9134            1 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9135            1 :             ),
    9136            1 :             (
    9137            1 :                 get_key(4),
    9138            1 :                 Lsn(0x30),
    9139            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9140            1 :             ),
    9141            1 :             (
    9142            1 :                 get_key(5),
    9143            1 :                 Lsn(0x20),
    9144            1 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9145            1 :             ),
    9146            1 :             (
    9147            1 :                 get_key(5),
    9148            1 :                 Lsn(0x30),
    9149            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9150            1 :             ),
    9151            1 :         ];
    9152            1 :         let image1 = vec![(get_key(1), "0x10".into())];
    9153            1 : 
    9154            1 :         let tline = tenant
    9155            1 :             .create_test_timeline_with_layers(
    9156            1 :                 TIMELINE_ID,
    9157            1 :                 Lsn(0x10),
    9158            1 :                 DEFAULT_PG_VERSION,
    9159            1 :                 &ctx,
    9160            1 :                 Vec::new(), // in-memory layers
    9161            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9162            1 :                     Lsn(0x10)..Lsn(0x40),
    9163            1 :                     delta1,
    9164            1 :                 )], // delta layers
    9165            1 :                 vec![(Lsn(0x10), image1)], // image layers
    9166            1 :                 Lsn(0x50),
    9167            1 :             )
    9168            1 :             .await?;
    9169            1 : 
    9170            1 :         assert_eq!(
    9171            1 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9172            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9173            1 :         );
    9174            1 :         assert_eq!(
    9175            1 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9176            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9177            1 :         );
    9178            1 : 
    9179            1 :         // Need to remove the limit of "Neon WAL redo requires base image".
    9180            1 : 
    9181            1 :         assert_eq!(
    9182            1 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9183            1 :             Bytes::from_static(b"c")
    9184            1 :         );
    9185            1 :         assert_eq!(
    9186            1 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9187            1 :             Bytes::from_static(b"ij")
    9188            1 :         );
    9189            1 : 
    9190            1 :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9191            1 :         // cannot enable this assertion in the unit test.
    9192            1 :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9193            1 : 
    9194            1 :         Ok(())
    9195            1 :     }
    9196              : 
    9197              :     #[tokio::test(start_paused = true)]
    9198            1 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9199            1 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9200            1 :             .await
    9201            1 :             .unwrap()
    9202            1 :             .load()
    9203            1 :             .await;
    9204            1 :         // Advance to the lsn lease deadline so that GC is not blocked by
    9205            1 :         // initial transition into AttachedSingle.
    9206            1 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    9207            1 :         tokio::time::resume();
    9208            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9209            1 : 
    9210            1 :         let end_lsn = Lsn(0x100);
    9211            1 :         let image_layers = (0x20..=0x90)
    9212            1 :             .step_by(0x10)
    9213            8 :             .map(|n| {
    9214            8 :                 (
    9215            8 :                     Lsn(n),
    9216            8 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    9217            8 :                 )
    9218            8 :             })
    9219            1 :             .collect();
    9220            1 : 
    9221            1 :         let timeline = tenant
    9222            1 :             .create_test_timeline_with_layers(
    9223            1 :                 TIMELINE_ID,
    9224            1 :                 Lsn(0x10),
    9225            1 :                 DEFAULT_PG_VERSION,
    9226            1 :                 &ctx,
    9227            1 :                 Vec::new(), // in-memory layers
    9228            1 :                 Vec::new(),
    9229            1 :                 image_layers,
    9230            1 :                 end_lsn,
    9231            1 :             )
    9232            1 :             .await?;
    9233            1 : 
    9234            1 :         let leased_lsns = [0x30, 0x50, 0x70];
    9235            1 :         let mut leases = Vec::new();
    9236            3 :         leased_lsns.iter().for_each(|n| {
    9237            3 :             leases.push(
    9238            3 :                 timeline
    9239            3 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9240            3 :                     .expect("lease request should succeed"),
    9241            3 :             );
    9242            3 :         });
    9243            1 : 
    9244            1 :         let updated_lease_0 = timeline
    9245            1 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9246            1 :             .expect("lease renewal should succeed");
    9247            1 :         assert_eq!(
    9248            1 :             updated_lease_0.valid_until, leases[0].valid_until,
    9249            1 :             " Renewing with shorter lease should not change the lease."
    9250            1 :         );
    9251            1 : 
    9252            1 :         let updated_lease_1 = timeline
    9253            1 :             .renew_lsn_lease(
    9254            1 :                 Lsn(leased_lsns[1]),
    9255            1 :                 timeline.get_lsn_lease_length() * 2,
    9256            1 :                 &ctx,
    9257            1 :             )
    9258            1 :             .expect("lease renewal should succeed");
    9259            1 :         assert!(
    9260            1 :             updated_lease_1.valid_until > leases[1].valid_until,
    9261            1 :             "Renewing with a long lease should renew lease with later expiration time."
    9262            1 :         );
    9263            1 : 
    9264            1 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9265            1 :         info!(
    9266            1 :             "applied_gc_cutoff_lsn: {}",
    9267            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9268            1 :         );
    9269            1 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9270            1 : 
    9271            1 :         let res = tenant
    9272            1 :             .gc_iteration(
    9273            1 :                 Some(TIMELINE_ID),
    9274            1 :                 0,
    9275            1 :                 Duration::ZERO,
    9276            1 :                 &CancellationToken::new(),
    9277            1 :                 &ctx,
    9278            1 :             )
    9279            1 :             .await
    9280            1 :             .unwrap();
    9281            1 : 
    9282            1 :         // Keeping everything <= Lsn(0x80) b/c leases:
    9283            1 :         // 0/10: initdb layer
    9284            1 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9285            1 :         assert_eq!(res.layers_needed_by_leases, 7);
    9286            1 :         // Keeping 0/90 b/c it is the latest layer.
    9287            1 :         assert_eq!(res.layers_not_updated, 1);
    9288            1 :         // Removed 0/80.
    9289            1 :         assert_eq!(res.layers_removed, 1);
    9290            1 : 
    9291            1 :         // Make lease on a already GC-ed LSN.
    9292            1 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9293            1 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9294            1 :         timeline
    9295            1 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9296            1 :             .expect_err("lease request on GC-ed LSN should fail");
    9297            1 : 
    9298            1 :         // Should still be able to renew a currently valid lease
    9299            1 :         // Assumption: original lease to is still valid for 0/50.
    9300            1 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9301            1 :         timeline
    9302            1 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9303            1 :             .expect("lease renewal with validation should succeed");
    9304            1 : 
    9305            1 :         Ok(())
    9306            1 :     }
    9307              : 
    9308              :     #[cfg(feature = "testing")]
    9309              :     #[tokio::test]
    9310            1 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9311            1 :         test_simple_bottom_most_compaction_deltas_helper(
    9312            1 :             "test_simple_bottom_most_compaction_deltas_1",
    9313            1 :             false,
    9314            1 :         )
    9315            1 :         .await
    9316            1 :     }
    9317              : 
    9318              :     #[cfg(feature = "testing")]
    9319              :     #[tokio::test]
    9320            1 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9321            1 :         test_simple_bottom_most_compaction_deltas_helper(
    9322            1 :             "test_simple_bottom_most_compaction_deltas_2",
    9323            1 :             true,
    9324            1 :         )
    9325            1 :         .await
    9326            1 :     }
    9327              : 
    9328              :     #[cfg(feature = "testing")]
    9329            2 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9330            2 :         test_name: &'static str,
    9331            2 :         use_delta_bottom_layer: bool,
    9332            2 :     ) -> anyhow::Result<()> {
    9333            2 :         let harness = TenantHarness::create(test_name).await?;
    9334            2 :         let (tenant, ctx) = harness.load().await;
    9335              : 
    9336          138 :         fn get_key(id: u32) -> Key {
    9337          138 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9338          138 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9339          138 :             key.field6 = id;
    9340          138 :             key
    9341          138 :         }
    9342              : 
    9343              :         // We create
    9344              :         // - one bottom-most image layer,
    9345              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9346              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9347              :         // - a delta layer D3 above the horizon.
    9348              :         //
    9349              :         //                             | D3 |
    9350              :         //  | D1 |
    9351              :         // -|    |-- gc horizon -----------------
    9352              :         //  |    |                | D2 |
    9353              :         // --------- img layer ------------------
    9354              :         //
    9355              :         // What we should expact from this compaction is:
    9356              :         //                             | D3 |
    9357              :         //  | Part of D1 |
    9358              :         // --------- img layer with D1+D2 at GC horizon------------------
    9359              : 
    9360              :         // img layer at 0x10
    9361            2 :         let img_layer = (0..10)
    9362           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9363            2 :             .collect_vec();
    9364            2 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9365            2 :         let delta4 = (0..10)
    9366           20 :             .map(|id| {
    9367           20 :                 (
    9368           20 :                     get_key(id),
    9369           20 :                     Lsn(0x08),
    9370           20 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9371           20 :                 )
    9372           20 :             })
    9373            2 :             .collect_vec();
    9374            2 : 
    9375            2 :         let delta1 = vec![
    9376            2 :             (
    9377            2 :                 get_key(1),
    9378            2 :                 Lsn(0x20),
    9379            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9380            2 :             ),
    9381            2 :             (
    9382            2 :                 get_key(2),
    9383            2 :                 Lsn(0x30),
    9384            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9385            2 :             ),
    9386            2 :             (
    9387            2 :                 get_key(3),
    9388            2 :                 Lsn(0x28),
    9389            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9390            2 :             ),
    9391            2 :             (
    9392            2 :                 get_key(3),
    9393            2 :                 Lsn(0x30),
    9394            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9395            2 :             ),
    9396            2 :             (
    9397            2 :                 get_key(3),
    9398            2 :                 Lsn(0x40),
    9399            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9400            2 :             ),
    9401            2 :         ];
    9402            2 :         let delta2 = vec![
    9403            2 :             (
    9404            2 :                 get_key(5),
    9405            2 :                 Lsn(0x20),
    9406            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9407            2 :             ),
    9408            2 :             (
    9409            2 :                 get_key(6),
    9410            2 :                 Lsn(0x20),
    9411            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9412            2 :             ),
    9413            2 :         ];
    9414            2 :         let delta3 = vec![
    9415            2 :             (
    9416            2 :                 get_key(8),
    9417            2 :                 Lsn(0x48),
    9418            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9419            2 :             ),
    9420            2 :             (
    9421            2 :                 get_key(9),
    9422            2 :                 Lsn(0x48),
    9423            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9424            2 :             ),
    9425            2 :         ];
    9426              : 
    9427            2 :         let tline = if use_delta_bottom_layer {
    9428            1 :             tenant
    9429            1 :                 .create_test_timeline_with_layers(
    9430            1 :                     TIMELINE_ID,
    9431            1 :                     Lsn(0x08),
    9432            1 :                     DEFAULT_PG_VERSION,
    9433            1 :                     &ctx,
    9434            1 :                     Vec::new(), // in-memory layers
    9435            1 :                     vec![
    9436            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9437            1 :                             Lsn(0x08)..Lsn(0x10),
    9438            1 :                             delta4,
    9439            1 :                         ),
    9440            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9441            1 :                             Lsn(0x20)..Lsn(0x48),
    9442            1 :                             delta1,
    9443            1 :                         ),
    9444            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9445            1 :                             Lsn(0x20)..Lsn(0x48),
    9446            1 :                             delta2,
    9447            1 :                         ),
    9448            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9449            1 :                             Lsn(0x48)..Lsn(0x50),
    9450            1 :                             delta3,
    9451            1 :                         ),
    9452            1 :                     ], // delta layers
    9453            1 :                     vec![],     // image layers
    9454            1 :                     Lsn(0x50),
    9455            1 :                 )
    9456            1 :                 .await?
    9457              :         } else {
    9458            1 :             tenant
    9459            1 :                 .create_test_timeline_with_layers(
    9460            1 :                     TIMELINE_ID,
    9461            1 :                     Lsn(0x10),
    9462            1 :                     DEFAULT_PG_VERSION,
    9463            1 :                     &ctx,
    9464            1 :                     Vec::new(), // in-memory layers
    9465            1 :                     vec![
    9466            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9467            1 :                             Lsn(0x10)..Lsn(0x48),
    9468            1 :                             delta1,
    9469            1 :                         ),
    9470            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9471            1 :                             Lsn(0x10)..Lsn(0x48),
    9472            1 :                             delta2,
    9473            1 :                         ),
    9474            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9475            1 :                             Lsn(0x48)..Lsn(0x50),
    9476            1 :                             delta3,
    9477            1 :                         ),
    9478            1 :                     ], // delta layers
    9479            1 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9480            1 :                     Lsn(0x50),
    9481            1 :                 )
    9482            1 :                 .await?
    9483              :         };
    9484              :         {
    9485            2 :             tline
    9486            2 :                 .applied_gc_cutoff_lsn
    9487            2 :                 .lock_for_write()
    9488            2 :                 .store_and_unlock(Lsn(0x30))
    9489            2 :                 .wait()
    9490            2 :                 .await;
    9491              :             // Update GC info
    9492            2 :             let mut guard = tline.gc_info.write().unwrap();
    9493            2 :             *guard = GcInfo {
    9494            2 :                 retain_lsns: vec![],
    9495            2 :                 cutoffs: GcCutoffs {
    9496            2 :                     time: Some(Lsn(0x30)),
    9497            2 :                     space: Lsn(0x30),
    9498            2 :                 },
    9499            2 :                 leases: Default::default(),
    9500            2 :                 within_ancestor_pitr: false,
    9501            2 :             };
    9502            2 :         }
    9503            2 : 
    9504            2 :         let expected_result = [
    9505            2 :             Bytes::from_static(b"value 0@0x10"),
    9506            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9507            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9508            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9509            2 :             Bytes::from_static(b"value 4@0x10"),
    9510            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9511            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9512            2 :             Bytes::from_static(b"value 7@0x10"),
    9513            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9514            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9515            2 :         ];
    9516            2 : 
    9517            2 :         let expected_result_at_gc_horizon = [
    9518            2 :             Bytes::from_static(b"value 0@0x10"),
    9519            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9520            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9521            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9522            2 :             Bytes::from_static(b"value 4@0x10"),
    9523            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9524            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9525            2 :             Bytes::from_static(b"value 7@0x10"),
    9526            2 :             Bytes::from_static(b"value 8@0x10"),
    9527            2 :             Bytes::from_static(b"value 9@0x10"),
    9528            2 :         ];
    9529              : 
    9530           22 :         for idx in 0..10 {
    9531           20 :             assert_eq!(
    9532           20 :                 tline
    9533           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9534           20 :                     .await
    9535           20 :                     .unwrap(),
    9536           20 :                 &expected_result[idx]
    9537              :             );
    9538           20 :             assert_eq!(
    9539           20 :                 tline
    9540           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9541           20 :                     .await
    9542           20 :                     .unwrap(),
    9543           20 :                 &expected_result_at_gc_horizon[idx]
    9544              :             );
    9545              :         }
    9546              : 
    9547            2 :         let cancel = CancellationToken::new();
    9548            2 :         tline
    9549            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9550            2 :             .await
    9551            2 :             .unwrap();
    9552              : 
    9553           22 :         for idx in 0..10 {
    9554           20 :             assert_eq!(
    9555           20 :                 tline
    9556           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9557           20 :                     .await
    9558           20 :                     .unwrap(),
    9559           20 :                 &expected_result[idx]
    9560              :             );
    9561           20 :             assert_eq!(
    9562           20 :                 tline
    9563           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9564           20 :                     .await
    9565           20 :                     .unwrap(),
    9566           20 :                 &expected_result_at_gc_horizon[idx]
    9567              :             );
    9568              :         }
    9569              : 
    9570              :         // increase GC horizon and compact again
    9571              :         {
    9572            2 :             tline
    9573            2 :                 .applied_gc_cutoff_lsn
    9574            2 :                 .lock_for_write()
    9575            2 :                 .store_and_unlock(Lsn(0x40))
    9576            2 :                 .wait()
    9577            2 :                 .await;
    9578              :             // Update GC info
    9579            2 :             let mut guard = tline.gc_info.write().unwrap();
    9580            2 :             guard.cutoffs.time = Some(Lsn(0x40));
    9581            2 :             guard.cutoffs.space = Lsn(0x40);
    9582            2 :         }
    9583            2 :         tline
    9584            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9585            2 :             .await
    9586            2 :             .unwrap();
    9587            2 : 
    9588            2 :         Ok(())
    9589            2 :     }
    9590              : 
    9591              :     #[cfg(feature = "testing")]
    9592              :     #[tokio::test]
    9593            1 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9594            1 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9595            1 :         let (tenant, ctx) = harness.load().await;
    9596            1 :         let tline = tenant
    9597            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9598            1 :             .await?;
    9599            1 :         tline.force_advance_lsn(Lsn(0x70));
    9600            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9601            1 :         let history = vec![
    9602            1 :             (
    9603            1 :                 key,
    9604            1 :                 Lsn(0x10),
    9605            1 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9606            1 :             ),
    9607            1 :             (
    9608            1 :                 key,
    9609            1 :                 Lsn(0x20),
    9610            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9611            1 :             ),
    9612            1 :             (
    9613            1 :                 key,
    9614            1 :                 Lsn(0x30),
    9615            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9616            1 :             ),
    9617            1 :             (
    9618            1 :                 key,
    9619            1 :                 Lsn(0x40),
    9620            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9621            1 :             ),
    9622            1 :             (
    9623            1 :                 key,
    9624            1 :                 Lsn(0x50),
    9625            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9626            1 :             ),
    9627            1 :             (
    9628            1 :                 key,
    9629            1 :                 Lsn(0x60),
    9630            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9631            1 :             ),
    9632            1 :             (
    9633            1 :                 key,
    9634            1 :                 Lsn(0x70),
    9635            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9636            1 :             ),
    9637            1 :             (
    9638            1 :                 key,
    9639            1 :                 Lsn(0x80),
    9640            1 :                 Value::Image(Bytes::copy_from_slice(
    9641            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9642            1 :                 )),
    9643            1 :             ),
    9644            1 :             (
    9645            1 :                 key,
    9646            1 :                 Lsn(0x90),
    9647            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9648            1 :             ),
    9649            1 :         ];
    9650            1 :         let res = tline
    9651            1 :             .generate_key_retention(
    9652            1 :                 key,
    9653            1 :                 &history,
    9654            1 :                 Lsn(0x60),
    9655            1 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9656            1 :                 3,
    9657            1 :                 None,
    9658            1 :                 true,
    9659            1 :             )
    9660            1 :             .await
    9661            1 :             .unwrap();
    9662            1 :         let expected_res = KeyHistoryRetention {
    9663            1 :             below_horizon: vec![
    9664            1 :                 (
    9665            1 :                     Lsn(0x20),
    9666            1 :                     KeyLogAtLsn(vec![(
    9667            1 :                         Lsn(0x20),
    9668            1 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9669            1 :                     )]),
    9670            1 :                 ),
    9671            1 :                 (
    9672            1 :                     Lsn(0x40),
    9673            1 :                     KeyLogAtLsn(vec![
    9674            1 :                         (
    9675            1 :                             Lsn(0x30),
    9676            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9677            1 :                         ),
    9678            1 :                         (
    9679            1 :                             Lsn(0x40),
    9680            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9681            1 :                         ),
    9682            1 :                     ]),
    9683            1 :                 ),
    9684            1 :                 (
    9685            1 :                     Lsn(0x50),
    9686            1 :                     KeyLogAtLsn(vec![(
    9687            1 :                         Lsn(0x50),
    9688            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9689            1 :                     )]),
    9690            1 :                 ),
    9691            1 :                 (
    9692            1 :                     Lsn(0x60),
    9693            1 :                     KeyLogAtLsn(vec![(
    9694            1 :                         Lsn(0x60),
    9695            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9696            1 :                     )]),
    9697            1 :                 ),
    9698            1 :             ],
    9699            1 :             above_horizon: KeyLogAtLsn(vec![
    9700            1 :                 (
    9701            1 :                     Lsn(0x70),
    9702            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9703            1 :                 ),
    9704            1 :                 (
    9705            1 :                     Lsn(0x80),
    9706            1 :                     Value::Image(Bytes::copy_from_slice(
    9707            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9708            1 :                     )),
    9709            1 :                 ),
    9710            1 :                 (
    9711            1 :                     Lsn(0x90),
    9712            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9713            1 :                 ),
    9714            1 :             ]),
    9715            1 :         };
    9716            1 :         assert_eq!(res, expected_res);
    9717            1 : 
    9718            1 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9719            1 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9720            1 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9721            1 :         // For example, we have
    9722            1 :         // ```plain
    9723            1 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9724            1 :         // ```
    9725            1 :         // Now the GC horizon moves up, and we have
    9726            1 :         // ```plain
    9727            1 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9728            1 :         // ```
    9729            1 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9730            1 :         // We will end up with
    9731            1 :         // ```plain
    9732            1 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9733            1 :         // ```
    9734            1 :         // Now we run the GC-compaction, and this key does not have a full history.
    9735            1 :         // We should be able to handle this partial history and drop everything before the
    9736            1 :         // gc_horizon image.
    9737            1 : 
    9738            1 :         let history = vec![
    9739            1 :             (
    9740            1 :                 key,
    9741            1 :                 Lsn(0x20),
    9742            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9743            1 :             ),
    9744            1 :             (
    9745            1 :                 key,
    9746            1 :                 Lsn(0x30),
    9747            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9748            1 :             ),
    9749            1 :             (
    9750            1 :                 key,
    9751            1 :                 Lsn(0x40),
    9752            1 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9753            1 :             ),
    9754            1 :             (
    9755            1 :                 key,
    9756            1 :                 Lsn(0x50),
    9757            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9758            1 :             ),
    9759            1 :             (
    9760            1 :                 key,
    9761            1 :                 Lsn(0x60),
    9762            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9763            1 :             ),
    9764            1 :             (
    9765            1 :                 key,
    9766            1 :                 Lsn(0x70),
    9767            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9768            1 :             ),
    9769            1 :             (
    9770            1 :                 key,
    9771            1 :                 Lsn(0x80),
    9772            1 :                 Value::Image(Bytes::copy_from_slice(
    9773            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9774            1 :                 )),
    9775            1 :             ),
    9776            1 :             (
    9777            1 :                 key,
    9778            1 :                 Lsn(0x90),
    9779            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9780            1 :             ),
    9781            1 :         ];
    9782            1 :         let res = tline
    9783            1 :             .generate_key_retention(
    9784            1 :                 key,
    9785            1 :                 &history,
    9786            1 :                 Lsn(0x60),
    9787            1 :                 &[Lsn(0x40), Lsn(0x50)],
    9788            1 :                 3,
    9789            1 :                 None,
    9790            1 :                 true,
    9791            1 :             )
    9792            1 :             .await
    9793            1 :             .unwrap();
    9794            1 :         let expected_res = KeyHistoryRetention {
    9795            1 :             below_horizon: vec![
    9796            1 :                 (
    9797            1 :                     Lsn(0x40),
    9798            1 :                     KeyLogAtLsn(vec![(
    9799            1 :                         Lsn(0x40),
    9800            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9801            1 :                     )]),
    9802            1 :                 ),
    9803            1 :                 (
    9804            1 :                     Lsn(0x50),
    9805            1 :                     KeyLogAtLsn(vec![(
    9806            1 :                         Lsn(0x50),
    9807            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9808            1 :                     )]),
    9809            1 :                 ),
    9810            1 :                 (
    9811            1 :                     Lsn(0x60),
    9812            1 :                     KeyLogAtLsn(vec![(
    9813            1 :                         Lsn(0x60),
    9814            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9815            1 :                     )]),
    9816            1 :                 ),
    9817            1 :             ],
    9818            1 :             above_horizon: KeyLogAtLsn(vec![
    9819            1 :                 (
    9820            1 :                     Lsn(0x70),
    9821            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9822            1 :                 ),
    9823            1 :                 (
    9824            1 :                     Lsn(0x80),
    9825            1 :                     Value::Image(Bytes::copy_from_slice(
    9826            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9827            1 :                     )),
    9828            1 :                 ),
    9829            1 :                 (
    9830            1 :                     Lsn(0x90),
    9831            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9832            1 :                 ),
    9833            1 :             ]),
    9834            1 :         };
    9835            1 :         assert_eq!(res, expected_res);
    9836            1 : 
    9837            1 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9838            1 :         // the ancestor image in the test case.
    9839            1 : 
    9840            1 :         let history = vec![
    9841            1 :             (
    9842            1 :                 key,
    9843            1 :                 Lsn(0x20),
    9844            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9845            1 :             ),
    9846            1 :             (
    9847            1 :                 key,
    9848            1 :                 Lsn(0x30),
    9849            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9850            1 :             ),
    9851            1 :             (
    9852            1 :                 key,
    9853            1 :                 Lsn(0x40),
    9854            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9855            1 :             ),
    9856            1 :             (
    9857            1 :                 key,
    9858            1 :                 Lsn(0x70),
    9859            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9860            1 :             ),
    9861            1 :         ];
    9862            1 :         let res = tline
    9863            1 :             .generate_key_retention(
    9864            1 :                 key,
    9865            1 :                 &history,
    9866            1 :                 Lsn(0x60),
    9867            1 :                 &[],
    9868            1 :                 3,
    9869            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9870            1 :                 true,
    9871            1 :             )
    9872            1 :             .await
    9873            1 :             .unwrap();
    9874            1 :         let expected_res = KeyHistoryRetention {
    9875            1 :             below_horizon: vec![(
    9876            1 :                 Lsn(0x60),
    9877            1 :                 KeyLogAtLsn(vec![(
    9878            1 :                     Lsn(0x60),
    9879            1 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9880            1 :                 )]),
    9881            1 :             )],
    9882            1 :             above_horizon: KeyLogAtLsn(vec![(
    9883            1 :                 Lsn(0x70),
    9884            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9885            1 :             )]),
    9886            1 :         };
    9887            1 :         assert_eq!(res, expected_res);
    9888            1 : 
    9889            1 :         let history = vec![
    9890            1 :             (
    9891            1 :                 key,
    9892            1 :                 Lsn(0x20),
    9893            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9894            1 :             ),
    9895            1 :             (
    9896            1 :                 key,
    9897            1 :                 Lsn(0x40),
    9898            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9899            1 :             ),
    9900            1 :             (
    9901            1 :                 key,
    9902            1 :                 Lsn(0x60),
    9903            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9904            1 :             ),
    9905            1 :             (
    9906            1 :                 key,
    9907            1 :                 Lsn(0x70),
    9908            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9909            1 :             ),
    9910            1 :         ];
    9911            1 :         let res = tline
    9912            1 :             .generate_key_retention(
    9913            1 :                 key,
    9914            1 :                 &history,
    9915            1 :                 Lsn(0x60),
    9916            1 :                 &[Lsn(0x30)],
    9917            1 :                 3,
    9918            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9919            1 :                 true,
    9920            1 :             )
    9921            1 :             .await
    9922            1 :             .unwrap();
    9923            1 :         let expected_res = KeyHistoryRetention {
    9924            1 :             below_horizon: vec![
    9925            1 :                 (
    9926            1 :                     Lsn(0x30),
    9927            1 :                     KeyLogAtLsn(vec![(
    9928            1 :                         Lsn(0x20),
    9929            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9930            1 :                     )]),
    9931            1 :                 ),
    9932            1 :                 (
    9933            1 :                     Lsn(0x60),
    9934            1 :                     KeyLogAtLsn(vec![(
    9935            1 :                         Lsn(0x60),
    9936            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9937            1 :                     )]),
    9938            1 :                 ),
    9939            1 :             ],
    9940            1 :             above_horizon: KeyLogAtLsn(vec![(
    9941            1 :                 Lsn(0x70),
    9942            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9943            1 :             )]),
    9944            1 :         };
    9945            1 :         assert_eq!(res, expected_res);
    9946            1 : 
    9947            1 :         Ok(())
    9948            1 :     }
    9949              : 
    9950              :     #[cfg(feature = "testing")]
    9951              :     #[tokio::test]
    9952            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9953            1 :         let harness =
    9954            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9955            1 :         let (tenant, ctx) = harness.load().await;
    9956            1 : 
    9957          259 :         fn get_key(id: u32) -> Key {
    9958          259 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9959          259 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9960          259 :             key.field6 = id;
    9961          259 :             key
    9962          259 :         }
    9963            1 : 
    9964            1 :         let img_layer = (0..10)
    9965           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9966            1 :             .collect_vec();
    9967            1 : 
    9968            1 :         let delta1 = vec![
    9969            1 :             (
    9970            1 :                 get_key(1),
    9971            1 :                 Lsn(0x20),
    9972            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9973            1 :             ),
    9974            1 :             (
    9975            1 :                 get_key(2),
    9976            1 :                 Lsn(0x30),
    9977            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9978            1 :             ),
    9979            1 :             (
    9980            1 :                 get_key(3),
    9981            1 :                 Lsn(0x28),
    9982            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9983            1 :             ),
    9984            1 :             (
    9985            1 :                 get_key(3),
    9986            1 :                 Lsn(0x30),
    9987            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9988            1 :             ),
    9989            1 :             (
    9990            1 :                 get_key(3),
    9991            1 :                 Lsn(0x40),
    9992            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9993            1 :             ),
    9994            1 :         ];
    9995            1 :         let delta2 = vec![
    9996            1 :             (
    9997            1 :                 get_key(5),
    9998            1 :                 Lsn(0x20),
    9999            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10000            1 :             ),
   10001            1 :             (
   10002            1 :                 get_key(6),
   10003            1 :                 Lsn(0x20),
   10004            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10005            1 :             ),
   10006            1 :         ];
   10007            1 :         let delta3 = vec![
   10008            1 :             (
   10009            1 :                 get_key(8),
   10010            1 :                 Lsn(0x48),
   10011            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10012            1 :             ),
   10013            1 :             (
   10014            1 :                 get_key(9),
   10015            1 :                 Lsn(0x48),
   10016            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10017            1 :             ),
   10018            1 :         ];
   10019            1 : 
   10020            1 :         let tline = tenant
   10021            1 :             .create_test_timeline_with_layers(
   10022            1 :                 TIMELINE_ID,
   10023            1 :                 Lsn(0x10),
   10024            1 :                 DEFAULT_PG_VERSION,
   10025            1 :                 &ctx,
   10026            1 :                 Vec::new(), // in-memory layers
   10027            1 :                 vec![
   10028            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
   10029            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
   10030            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10031            1 :                 ], // delta layers
   10032            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10033            1 :                 Lsn(0x50),
   10034            1 :             )
   10035            1 :             .await?;
   10036            1 :         {
   10037            1 :             tline
   10038            1 :                 .applied_gc_cutoff_lsn
   10039            1 :                 .lock_for_write()
   10040            1 :                 .store_and_unlock(Lsn(0x30))
   10041            1 :                 .wait()
   10042            1 :                 .await;
   10043            1 :             // Update GC info
   10044            1 :             let mut guard = tline.gc_info.write().unwrap();
   10045            1 :             *guard = GcInfo {
   10046            1 :                 retain_lsns: vec![
   10047            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10048            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10049            1 :                 ],
   10050            1 :                 cutoffs: GcCutoffs {
   10051            1 :                     time: Some(Lsn(0x30)),
   10052            1 :                     space: Lsn(0x30),
   10053            1 :                 },
   10054            1 :                 leases: Default::default(),
   10055            1 :                 within_ancestor_pitr: false,
   10056            1 :             };
   10057            1 :         }
   10058            1 : 
   10059            1 :         let expected_result = [
   10060            1 :             Bytes::from_static(b"value 0@0x10"),
   10061            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10062            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10063            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10064            1 :             Bytes::from_static(b"value 4@0x10"),
   10065            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10066            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10067            1 :             Bytes::from_static(b"value 7@0x10"),
   10068            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10069            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10070            1 :         ];
   10071            1 : 
   10072            1 :         let expected_result_at_gc_horizon = [
   10073            1 :             Bytes::from_static(b"value 0@0x10"),
   10074            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10075            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10076            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
   10077            1 :             Bytes::from_static(b"value 4@0x10"),
   10078            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10079            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10080            1 :             Bytes::from_static(b"value 7@0x10"),
   10081            1 :             Bytes::from_static(b"value 8@0x10"),
   10082            1 :             Bytes::from_static(b"value 9@0x10"),
   10083            1 :         ];
   10084            1 : 
   10085            1 :         let expected_result_at_lsn_20 = [
   10086            1 :             Bytes::from_static(b"value 0@0x10"),
   10087            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10088            1 :             Bytes::from_static(b"value 2@0x10"),
   10089            1 :             Bytes::from_static(b"value 3@0x10"),
   10090            1 :             Bytes::from_static(b"value 4@0x10"),
   10091            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10092            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10093            1 :             Bytes::from_static(b"value 7@0x10"),
   10094            1 :             Bytes::from_static(b"value 8@0x10"),
   10095            1 :             Bytes::from_static(b"value 9@0x10"),
   10096            1 :         ];
   10097            1 : 
   10098            1 :         let expected_result_at_lsn_10 = [
   10099            1 :             Bytes::from_static(b"value 0@0x10"),
   10100            1 :             Bytes::from_static(b"value 1@0x10"),
   10101            1 :             Bytes::from_static(b"value 2@0x10"),
   10102            1 :             Bytes::from_static(b"value 3@0x10"),
   10103            1 :             Bytes::from_static(b"value 4@0x10"),
   10104            1 :             Bytes::from_static(b"value 5@0x10"),
   10105            1 :             Bytes::from_static(b"value 6@0x10"),
   10106            1 :             Bytes::from_static(b"value 7@0x10"),
   10107            1 :             Bytes::from_static(b"value 8@0x10"),
   10108            1 :             Bytes::from_static(b"value 9@0x10"),
   10109            1 :         ];
   10110            1 : 
   10111            6 :         let verify_result = || async {
   10112            6 :             let gc_horizon = {
   10113            6 :                 let gc_info = tline.gc_info.read().unwrap();
   10114            6 :                 gc_info.cutoffs.time.unwrap_or_default()
   10115            1 :             };
   10116           66 :             for idx in 0..10 {
   10117           60 :                 assert_eq!(
   10118           60 :                     tline
   10119           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10120           60 :                         .await
   10121           60 :                         .unwrap(),
   10122           60 :                     &expected_result[idx]
   10123            1 :                 );
   10124           60 :                 assert_eq!(
   10125           60 :                     tline
   10126           60 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10127           60 :                         .await
   10128           60 :                         .unwrap(),
   10129           60 :                     &expected_result_at_gc_horizon[idx]
   10130            1 :                 );
   10131           60 :                 assert_eq!(
   10132           60 :                     tline
   10133           60 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10134           60 :                         .await
   10135           60 :                         .unwrap(),
   10136           60 :                     &expected_result_at_lsn_20[idx]
   10137            1 :                 );
   10138           60 :                 assert_eq!(
   10139           60 :                     tline
   10140           60 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10141           60 :                         .await
   10142           60 :                         .unwrap(),
   10143           60 :                     &expected_result_at_lsn_10[idx]
   10144            1 :                 );
   10145            1 :             }
   10146           12 :         };
   10147            1 : 
   10148            1 :         verify_result().await;
   10149            1 : 
   10150            1 :         let cancel = CancellationToken::new();
   10151            1 :         let mut dryrun_flags = EnumSet::new();
   10152            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10153            1 : 
   10154            1 :         tline
   10155            1 :             .compact_with_gc(
   10156            1 :                 &cancel,
   10157            1 :                 CompactOptions {
   10158            1 :                     flags: dryrun_flags,
   10159            1 :                     ..Default::default()
   10160            1 :                 },
   10161            1 :                 &ctx,
   10162            1 :             )
   10163            1 :             .await
   10164            1 :             .unwrap();
   10165            1 :         // 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
   10166            1 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10167            1 :         verify_result().await;
   10168            1 : 
   10169            1 :         tline
   10170            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10171            1 :             .await
   10172            1 :             .unwrap();
   10173            1 :         verify_result().await;
   10174            1 : 
   10175            1 :         // compact again
   10176            1 :         tline
   10177            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10178            1 :             .await
   10179            1 :             .unwrap();
   10180            1 :         verify_result().await;
   10181            1 : 
   10182            1 :         // increase GC horizon and compact again
   10183            1 :         {
   10184            1 :             tline
   10185            1 :                 .applied_gc_cutoff_lsn
   10186            1 :                 .lock_for_write()
   10187            1 :                 .store_and_unlock(Lsn(0x38))
   10188            1 :                 .wait()
   10189            1 :                 .await;
   10190            1 :             // Update GC info
   10191            1 :             let mut guard = tline.gc_info.write().unwrap();
   10192            1 :             guard.cutoffs.time = Some(Lsn(0x38));
   10193            1 :             guard.cutoffs.space = Lsn(0x38);
   10194            1 :         }
   10195            1 :         tline
   10196            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10197            1 :             .await
   10198            1 :             .unwrap();
   10199            1 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10200            1 : 
   10201            1 :         // not increasing the GC horizon and compact again
   10202            1 :         tline
   10203            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10204            1 :             .await
   10205            1 :             .unwrap();
   10206            1 :         verify_result().await;
   10207            1 : 
   10208            1 :         Ok(())
   10209            1 :     }
   10210              : 
   10211              :     #[cfg(feature = "testing")]
   10212              :     #[tokio::test]
   10213            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10214            1 :     {
   10215            1 :         let harness =
   10216            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10217            1 :                 .await?;
   10218            1 :         let (tenant, ctx) = harness.load().await;
   10219            1 : 
   10220          176 :         fn get_key(id: u32) -> Key {
   10221          176 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10222          176 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10223          176 :             key.field6 = id;
   10224          176 :             key
   10225          176 :         }
   10226            1 : 
   10227            1 :         let img_layer = (0..10)
   10228           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10229            1 :             .collect_vec();
   10230            1 : 
   10231            1 :         let delta1 = vec![
   10232            1 :             (
   10233            1 :                 get_key(1),
   10234            1 :                 Lsn(0x20),
   10235            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10236            1 :             ),
   10237            1 :             (
   10238            1 :                 get_key(1),
   10239            1 :                 Lsn(0x28),
   10240            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10241            1 :             ),
   10242            1 :         ];
   10243            1 :         let delta2 = vec![
   10244            1 :             (
   10245            1 :                 get_key(1),
   10246            1 :                 Lsn(0x30),
   10247            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10248            1 :             ),
   10249            1 :             (
   10250            1 :                 get_key(1),
   10251            1 :                 Lsn(0x38),
   10252            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10253            1 :             ),
   10254            1 :         ];
   10255            1 :         let delta3 = vec![
   10256            1 :             (
   10257            1 :                 get_key(8),
   10258            1 :                 Lsn(0x48),
   10259            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10260            1 :             ),
   10261            1 :             (
   10262            1 :                 get_key(9),
   10263            1 :                 Lsn(0x48),
   10264            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10265            1 :             ),
   10266            1 :         ];
   10267            1 : 
   10268            1 :         let tline = tenant
   10269            1 :             .create_test_timeline_with_layers(
   10270            1 :                 TIMELINE_ID,
   10271            1 :                 Lsn(0x10),
   10272            1 :                 DEFAULT_PG_VERSION,
   10273            1 :                 &ctx,
   10274            1 :                 Vec::new(), // in-memory layers
   10275            1 :                 vec![
   10276            1 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10277            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10278            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10279            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10280            1 :                 ], // delta layers
   10281            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10282            1 :                 Lsn(0x50),
   10283            1 :             )
   10284            1 :             .await?;
   10285            1 :         {
   10286            1 :             tline
   10287            1 :                 .applied_gc_cutoff_lsn
   10288            1 :                 .lock_for_write()
   10289            1 :                 .store_and_unlock(Lsn(0x30))
   10290            1 :                 .wait()
   10291            1 :                 .await;
   10292            1 :             // Update GC info
   10293            1 :             let mut guard = tline.gc_info.write().unwrap();
   10294            1 :             *guard = GcInfo {
   10295            1 :                 retain_lsns: vec![
   10296            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10297            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10298            1 :                 ],
   10299            1 :                 cutoffs: GcCutoffs {
   10300            1 :                     time: Some(Lsn(0x30)),
   10301            1 :                     space: Lsn(0x30),
   10302            1 :                 },
   10303            1 :                 leases: Default::default(),
   10304            1 :                 within_ancestor_pitr: false,
   10305            1 :             };
   10306            1 :         }
   10307            1 : 
   10308            1 :         let expected_result = [
   10309            1 :             Bytes::from_static(b"value 0@0x10"),
   10310            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10311            1 :             Bytes::from_static(b"value 2@0x10"),
   10312            1 :             Bytes::from_static(b"value 3@0x10"),
   10313            1 :             Bytes::from_static(b"value 4@0x10"),
   10314            1 :             Bytes::from_static(b"value 5@0x10"),
   10315            1 :             Bytes::from_static(b"value 6@0x10"),
   10316            1 :             Bytes::from_static(b"value 7@0x10"),
   10317            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10318            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10319            1 :         ];
   10320            1 : 
   10321            1 :         let expected_result_at_gc_horizon = [
   10322            1 :             Bytes::from_static(b"value 0@0x10"),
   10323            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10324            1 :             Bytes::from_static(b"value 2@0x10"),
   10325            1 :             Bytes::from_static(b"value 3@0x10"),
   10326            1 :             Bytes::from_static(b"value 4@0x10"),
   10327            1 :             Bytes::from_static(b"value 5@0x10"),
   10328            1 :             Bytes::from_static(b"value 6@0x10"),
   10329            1 :             Bytes::from_static(b"value 7@0x10"),
   10330            1 :             Bytes::from_static(b"value 8@0x10"),
   10331            1 :             Bytes::from_static(b"value 9@0x10"),
   10332            1 :         ];
   10333            1 : 
   10334            1 :         let expected_result_at_lsn_20 = [
   10335            1 :             Bytes::from_static(b"value 0@0x10"),
   10336            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10337            1 :             Bytes::from_static(b"value 2@0x10"),
   10338            1 :             Bytes::from_static(b"value 3@0x10"),
   10339            1 :             Bytes::from_static(b"value 4@0x10"),
   10340            1 :             Bytes::from_static(b"value 5@0x10"),
   10341            1 :             Bytes::from_static(b"value 6@0x10"),
   10342            1 :             Bytes::from_static(b"value 7@0x10"),
   10343            1 :             Bytes::from_static(b"value 8@0x10"),
   10344            1 :             Bytes::from_static(b"value 9@0x10"),
   10345            1 :         ];
   10346            1 : 
   10347            1 :         let expected_result_at_lsn_10 = [
   10348            1 :             Bytes::from_static(b"value 0@0x10"),
   10349            1 :             Bytes::from_static(b"value 1@0x10"),
   10350            1 :             Bytes::from_static(b"value 2@0x10"),
   10351            1 :             Bytes::from_static(b"value 3@0x10"),
   10352            1 :             Bytes::from_static(b"value 4@0x10"),
   10353            1 :             Bytes::from_static(b"value 5@0x10"),
   10354            1 :             Bytes::from_static(b"value 6@0x10"),
   10355            1 :             Bytes::from_static(b"value 7@0x10"),
   10356            1 :             Bytes::from_static(b"value 8@0x10"),
   10357            1 :             Bytes::from_static(b"value 9@0x10"),
   10358            1 :         ];
   10359            1 : 
   10360            4 :         let verify_result = || async {
   10361            4 :             let gc_horizon = {
   10362            4 :                 let gc_info = tline.gc_info.read().unwrap();
   10363            4 :                 gc_info.cutoffs.time.unwrap_or_default()
   10364            1 :             };
   10365           44 :             for idx in 0..10 {
   10366           40 :                 assert_eq!(
   10367           40 :                     tline
   10368           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10369           40 :                         .await
   10370           40 :                         .unwrap(),
   10371           40 :                     &expected_result[idx]
   10372            1 :                 );
   10373           40 :                 assert_eq!(
   10374           40 :                     tline
   10375           40 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10376           40 :                         .await
   10377           40 :                         .unwrap(),
   10378           40 :                     &expected_result_at_gc_horizon[idx]
   10379            1 :                 );
   10380           40 :                 assert_eq!(
   10381           40 :                     tline
   10382           40 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10383           40 :                         .await
   10384           40 :                         .unwrap(),
   10385           40 :                     &expected_result_at_lsn_20[idx]
   10386            1 :                 );
   10387           40 :                 assert_eq!(
   10388           40 :                     tline
   10389           40 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10390           40 :                         .await
   10391           40 :                         .unwrap(),
   10392           40 :                     &expected_result_at_lsn_10[idx]
   10393            1 :                 );
   10394            1 :             }
   10395            8 :         };
   10396            1 : 
   10397            1 :         verify_result().await;
   10398            1 : 
   10399            1 :         let cancel = CancellationToken::new();
   10400            1 :         let mut dryrun_flags = EnumSet::new();
   10401            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10402            1 : 
   10403            1 :         tline
   10404            1 :             .compact_with_gc(
   10405            1 :                 &cancel,
   10406            1 :                 CompactOptions {
   10407            1 :                     flags: dryrun_flags,
   10408            1 :                     ..Default::default()
   10409            1 :                 },
   10410            1 :                 &ctx,
   10411            1 :             )
   10412            1 :             .await
   10413            1 :             .unwrap();
   10414            1 :         // 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
   10415            1 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10416            1 :         verify_result().await;
   10417            1 : 
   10418            1 :         tline
   10419            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10420            1 :             .await
   10421            1 :             .unwrap();
   10422            1 :         verify_result().await;
   10423            1 : 
   10424            1 :         // compact again
   10425            1 :         tline
   10426            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10427            1 :             .await
   10428            1 :             .unwrap();
   10429            1 :         verify_result().await;
   10430            1 : 
   10431            1 :         Ok(())
   10432            1 :     }
   10433              : 
   10434              :     #[cfg(feature = "testing")]
   10435              :     #[tokio::test]
   10436            1 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10437            1 :         use models::CompactLsnRange;
   10438            1 : 
   10439            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10440            1 :         let (tenant, ctx) = harness.load().await;
   10441            1 : 
   10442           83 :         fn get_key(id: u32) -> Key {
   10443           83 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10444           83 :             key.field6 = id;
   10445           83 :             key
   10446           83 :         }
   10447            1 : 
   10448            1 :         let img_layer = (0..10)
   10449           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10450            1 :             .collect_vec();
   10451            1 : 
   10452            1 :         let delta1 = vec![
   10453            1 :             (
   10454            1 :                 get_key(1),
   10455            1 :                 Lsn(0x20),
   10456            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10457            1 :             ),
   10458            1 :             (
   10459            1 :                 get_key(2),
   10460            1 :                 Lsn(0x30),
   10461            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10462            1 :             ),
   10463            1 :             (
   10464            1 :                 get_key(3),
   10465            1 :                 Lsn(0x28),
   10466            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10467            1 :             ),
   10468            1 :             (
   10469            1 :                 get_key(3),
   10470            1 :                 Lsn(0x30),
   10471            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10472            1 :             ),
   10473            1 :             (
   10474            1 :                 get_key(3),
   10475            1 :                 Lsn(0x40),
   10476            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10477            1 :             ),
   10478            1 :         ];
   10479            1 :         let delta2 = vec![
   10480            1 :             (
   10481            1 :                 get_key(5),
   10482            1 :                 Lsn(0x20),
   10483            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10484            1 :             ),
   10485            1 :             (
   10486            1 :                 get_key(6),
   10487            1 :                 Lsn(0x20),
   10488            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10489            1 :             ),
   10490            1 :         ];
   10491            1 :         let delta3 = vec![
   10492            1 :             (
   10493            1 :                 get_key(8),
   10494            1 :                 Lsn(0x48),
   10495            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10496            1 :             ),
   10497            1 :             (
   10498            1 :                 get_key(9),
   10499            1 :                 Lsn(0x48),
   10500            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10501            1 :             ),
   10502            1 :         ];
   10503            1 : 
   10504            1 :         let parent_tline = tenant
   10505            1 :             .create_test_timeline_with_layers(
   10506            1 :                 TIMELINE_ID,
   10507            1 :                 Lsn(0x10),
   10508            1 :                 DEFAULT_PG_VERSION,
   10509            1 :                 &ctx,
   10510            1 :                 vec![],                       // in-memory layers
   10511            1 :                 vec![],                       // delta layers
   10512            1 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10513            1 :                 Lsn(0x18),
   10514            1 :             )
   10515            1 :             .await?;
   10516            1 : 
   10517            1 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10518            1 : 
   10519            1 :         let branch_tline = tenant
   10520            1 :             .branch_timeline_test_with_layers(
   10521            1 :                 &parent_tline,
   10522            1 :                 NEW_TIMELINE_ID,
   10523            1 :                 Some(Lsn(0x18)),
   10524            1 :                 &ctx,
   10525            1 :                 vec![
   10526            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10527            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10528            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10529            1 :                 ], // delta layers
   10530            1 :                 vec![], // image layers
   10531            1 :                 Lsn(0x50),
   10532            1 :             )
   10533            1 :             .await?;
   10534            1 : 
   10535            1 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10536            1 : 
   10537            1 :         {
   10538            1 :             parent_tline
   10539            1 :                 .applied_gc_cutoff_lsn
   10540            1 :                 .lock_for_write()
   10541            1 :                 .store_and_unlock(Lsn(0x10))
   10542            1 :                 .wait()
   10543            1 :                 .await;
   10544            1 :             // Update GC info
   10545            1 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10546            1 :             *guard = GcInfo {
   10547            1 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10548            1 :                 cutoffs: GcCutoffs {
   10549            1 :                     time: Some(Lsn(0x10)),
   10550            1 :                     space: Lsn(0x10),
   10551            1 :                 },
   10552            1 :                 leases: Default::default(),
   10553            1 :                 within_ancestor_pitr: false,
   10554            1 :             };
   10555            1 :         }
   10556            1 : 
   10557            1 :         {
   10558            1 :             branch_tline
   10559            1 :                 .applied_gc_cutoff_lsn
   10560            1 :                 .lock_for_write()
   10561            1 :                 .store_and_unlock(Lsn(0x50))
   10562            1 :                 .wait()
   10563            1 :                 .await;
   10564            1 :             // Update GC info
   10565            1 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10566            1 :             *guard = GcInfo {
   10567            1 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10568            1 :                 cutoffs: GcCutoffs {
   10569            1 :                     time: Some(Lsn(0x50)),
   10570            1 :                     space: Lsn(0x50),
   10571            1 :                 },
   10572            1 :                 leases: Default::default(),
   10573            1 :                 within_ancestor_pitr: false,
   10574            1 :             };
   10575            1 :         }
   10576            1 : 
   10577            1 :         let expected_result_at_gc_horizon = [
   10578            1 :             Bytes::from_static(b"value 0@0x10"),
   10579            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10580            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10581            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10582            1 :             Bytes::from_static(b"value 4@0x10"),
   10583            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10584            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10585            1 :             Bytes::from_static(b"value 7@0x10"),
   10586            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10587            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10588            1 :         ];
   10589            1 : 
   10590            1 :         let expected_result_at_lsn_40 = [
   10591            1 :             Bytes::from_static(b"value 0@0x10"),
   10592            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10593            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10594            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10595            1 :             Bytes::from_static(b"value 4@0x10"),
   10596            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10597            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10598            1 :             Bytes::from_static(b"value 7@0x10"),
   10599            1 :             Bytes::from_static(b"value 8@0x10"),
   10600            1 :             Bytes::from_static(b"value 9@0x10"),
   10601            1 :         ];
   10602            1 : 
   10603            3 :         let verify_result = || async {
   10604           33 :             for idx in 0..10 {
   10605           30 :                 assert_eq!(
   10606           30 :                     branch_tline
   10607           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10608           30 :                         .await
   10609           30 :                         .unwrap(),
   10610           30 :                     &expected_result_at_gc_horizon[idx]
   10611            1 :                 );
   10612           30 :                 assert_eq!(
   10613           30 :                     branch_tline
   10614           30 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10615           30 :                         .await
   10616           30 :                         .unwrap(),
   10617           30 :                     &expected_result_at_lsn_40[idx]
   10618            1 :                 );
   10619            1 :             }
   10620            6 :         };
   10621            1 : 
   10622            1 :         verify_result().await;
   10623            1 : 
   10624            1 :         let cancel = CancellationToken::new();
   10625            1 :         branch_tline
   10626            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10627            1 :             .await
   10628            1 :             .unwrap();
   10629            1 : 
   10630            1 :         verify_result().await;
   10631            1 : 
   10632            1 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10633            1 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10634            1 :         branch_tline
   10635            1 :             .compact_with_gc(
   10636            1 :                 &cancel,
   10637            1 :                 CompactOptions {
   10638            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10639            1 :                     ..Default::default()
   10640            1 :                 },
   10641            1 :                 &ctx,
   10642            1 :             )
   10643            1 :             .await
   10644            1 :             .unwrap();
   10645            1 : 
   10646            1 :         verify_result().await;
   10647            1 : 
   10648            1 :         Ok(())
   10649            1 :     }
   10650              : 
   10651              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10652              :     // Create an image arrangement where we have to read at different LSN ranges
   10653              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10654              :     // a delta layer. Like so:
   10655              :     //
   10656              :     //     A      B
   10657              :     // +----------------+ -> delta_layer
   10658              :     // |                |                           ^ lsn
   10659              :     // |       =========|-> nested_image_layer      |
   10660              :     // |       C        |                           |
   10661              :     // +----------------+                           |
   10662              :     // ======== -> baseline_image_layer             +-------> key
   10663              :     //
   10664              :     //
   10665              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10666              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10667              :     #[cfg(feature = "testing")]
   10668              :     #[tokio::test]
   10669            1 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10670            1 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10671            1 :         let (tenant, ctx) = harness.load().await;
   10672            1 : 
   10673            1 :         let will_init_keys = [2, 6];
   10674           22 :         fn get_key(id: u32) -> Key {
   10675           22 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10676           22 :             key.field6 = id;
   10677           22 :             key
   10678           22 :         }
   10679            1 : 
   10680            1 :         let mut expected_key_values = HashMap::new();
   10681            1 : 
   10682            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   10683            1 :         let mut baseline_img_layer = Vec::new();
   10684            6 :         for i in 0..5 {
   10685            5 :             let key = get_key(i);
   10686            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10687            5 : 
   10688            5 :             let removed = expected_key_values.insert(key, value.clone());
   10689            5 :             assert!(removed.is_none());
   10690            1 : 
   10691            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   10692            1 :         }
   10693            1 : 
   10694            1 :         let nested_image_layer_lsn = Lsn(0x50);
   10695            1 :         let mut nested_img_layer = Vec::new();
   10696            6 :         for i in 5..10 {
   10697            5 :             let key = get_key(i);
   10698            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10699            5 : 
   10700            5 :             let removed = expected_key_values.insert(key, value.clone());
   10701            5 :             assert!(removed.is_none());
   10702            1 : 
   10703            5 :             nested_img_layer.push((key, Bytes::from(value)));
   10704            1 :         }
   10705            1 : 
   10706            1 :         let mut delta_layer_spec = Vec::default();
   10707            1 :         let delta_layer_start_lsn = Lsn(0x20);
   10708            1 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10709            1 : 
   10710           11 :         for i in 0..10 {
   10711           10 :             let key = get_key(i);
   10712           10 :             let key_in_nested = nested_img_layer
   10713           10 :                 .iter()
   10714           40 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10715           10 :             let lsn = {
   10716           10 :                 if key_in_nested {
   10717            5 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10718            1 :                 } else {
   10719            5 :                     delta_layer_start_lsn
   10720            1 :                 }
   10721            1 :             };
   10722            1 : 
   10723           10 :             let will_init = will_init_keys.contains(&i);
   10724           10 :             if will_init {
   10725            2 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10726            2 : 
   10727            2 :                 expected_key_values.insert(key, "".to_string());
   10728            8 :             } else {
   10729            8 :                 let delta = format!("@{lsn}");
   10730            8 :                 delta_layer_spec.push((
   10731            8 :                     key,
   10732            8 :                     lsn,
   10733            8 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10734            8 :                 ));
   10735            8 : 
   10736            8 :                 expected_key_values
   10737            8 :                     .get_mut(&key)
   10738            8 :                     .expect("An image exists for each key")
   10739            8 :                     .push_str(delta.as_str());
   10740            8 :             }
   10741           10 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10742            1 :         }
   10743            1 : 
   10744            1 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10745            1 : 
   10746            1 :         assert!(
   10747            1 :             nested_image_layer_lsn > delta_layer_start_lsn
   10748            1 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10749            1 :         );
   10750            1 : 
   10751            1 :         let tline = tenant
   10752            1 :             .create_test_timeline_with_layers(
   10753            1 :                 TIMELINE_ID,
   10754            1 :                 baseline_image_layer_lsn,
   10755            1 :                 DEFAULT_PG_VERSION,
   10756            1 :                 &ctx,
   10757            1 :                 vec![], // in-memory layers
   10758            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10759            1 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10760            1 :                     delta_layer_spec,
   10761            1 :                 )], // delta layers
   10762            1 :                 vec![
   10763            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10764            1 :                     (nested_image_layer_lsn, nested_img_layer),
   10765            1 :                 ], // image layers
   10766            1 :                 delta_layer_end_lsn,
   10767            1 :             )
   10768            1 :             .await?;
   10769            1 : 
   10770            1 :         let query = VersionedKeySpaceQuery::uniform(
   10771            1 :             KeySpace::single(get_key(0)..get_key(10)),
   10772            1 :             delta_layer_end_lsn,
   10773            1 :         );
   10774            1 : 
   10775            1 :         let results = tline
   10776            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   10777            1 :             .await
   10778            1 :             .expect("No vectored errors");
   10779           11 :         for (key, res) in results {
   10780           10 :             let value = res.expect("No key errors");
   10781           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10782           10 :             assert_eq!(value, Bytes::from(expected_value));
   10783            1 :         }
   10784            1 : 
   10785            1 :         Ok(())
   10786            1 :     }
   10787              : 
   10788              :     #[cfg(feature = "testing")]
   10789              :     #[tokio::test]
   10790            1 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   10791            1 :         let harness =
   10792            1 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   10793            1 :         let (tenant, ctx) = harness.load().await;
   10794            1 : 
   10795            1 :         let will_init_keys = [2, 6];
   10796           32 :         fn get_key(id: u32) -> Key {
   10797           32 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10798           32 :             key.field6 = id;
   10799           32 :             key
   10800           32 :         }
   10801            1 : 
   10802            1 :         let mut expected_key_values = HashMap::new();
   10803            1 : 
   10804            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   10805            1 :         let mut baseline_img_layer = Vec::new();
   10806            6 :         for i in 0..5 {
   10807            5 :             let key = get_key(i);
   10808            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10809            5 : 
   10810            5 :             let removed = expected_key_values.insert(key, value.clone());
   10811            5 :             assert!(removed.is_none());
   10812            1 : 
   10813            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   10814            1 :         }
   10815            1 : 
   10816            1 :         let nested_image_layer_lsn = Lsn(0x50);
   10817            1 :         let mut nested_img_layer = Vec::new();
   10818            6 :         for i in 5..10 {
   10819            5 :             let key = get_key(i);
   10820            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10821            5 : 
   10822            5 :             let removed = expected_key_values.insert(key, value.clone());
   10823            5 :             assert!(removed.is_none());
   10824            1 : 
   10825            5 :             nested_img_layer.push((key, Bytes::from(value)));
   10826            1 :         }
   10827            1 : 
   10828            1 :         let frozen_layer = {
   10829            1 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   10830            1 :             let mut data = Vec::new();
   10831           11 :             for i in 0..10 {
   10832           10 :                 let key = get_key(i);
   10833           10 :                 let key_in_nested = nested_img_layer
   10834           10 :                     .iter()
   10835           40 :                     .any(|(key_with_img, _)| *key_with_img == key);
   10836           10 :                 let lsn = {
   10837           10 :                     if key_in_nested {
   10838            5 :                         Lsn(nested_image_layer_lsn.0 + 5)
   10839            1 :                     } else {
   10840            5 :                         lsn_range.start
   10841            1 :                     }
   10842            1 :                 };
   10843            1 : 
   10844           10 :                 let will_init = will_init_keys.contains(&i);
   10845           10 :                 if will_init {
   10846            2 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10847            2 : 
   10848            2 :                     expected_key_values.insert(key, "".to_string());
   10849            8 :                 } else {
   10850            8 :                     let delta = format!("@{lsn}");
   10851            8 :                     data.push((
   10852            8 :                         key,
   10853            8 :                         lsn,
   10854            8 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10855            8 :                     ));
   10856            8 : 
   10857            8 :                     expected_key_values
   10858            8 :                         .get_mut(&key)
   10859            8 :                         .expect("An image exists for each key")
   10860            8 :                         .push_str(delta.as_str());
   10861            8 :                 }
   10862            1 :             }
   10863            1 : 
   10864            1 :             InMemoryLayerTestDesc {
   10865            1 :                 lsn_range,
   10866            1 :                 is_open: false,
   10867            1 :                 data,
   10868            1 :             }
   10869            1 :         };
   10870            1 : 
   10871            1 :         let (open_layer, last_record_lsn) = {
   10872            1 :             let start_lsn = Lsn(0x70);
   10873            1 :             let mut data = Vec::new();
   10874            1 :             let mut end_lsn = Lsn(0);
   10875           11 :             for i in 0..10 {
   10876           10 :                 let key = get_key(i);
   10877           10 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   10878           10 :                 let delta = format!("@{lsn}");
   10879           10 :                 data.push((
   10880           10 :                     key,
   10881           10 :                     lsn,
   10882           10 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10883           10 :                 ));
   10884           10 : 
   10885           10 :                 expected_key_values
   10886           10 :                     .get_mut(&key)
   10887           10 :                     .expect("An image exists for each key")
   10888           10 :                     .push_str(delta.as_str());
   10889           10 : 
   10890           10 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   10891           10 :             }
   10892            1 : 
   10893            1 :             (
   10894            1 :                 InMemoryLayerTestDesc {
   10895            1 :                     lsn_range: start_lsn..Lsn::MAX,
   10896            1 :                     is_open: true,
   10897            1 :                     data,
   10898            1 :                 },
   10899            1 :                 end_lsn,
   10900            1 :             )
   10901            1 :         };
   10902            1 : 
   10903            1 :         assert!(
   10904            1 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   10905            1 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   10906            1 :         );
   10907            1 : 
   10908            1 :         let tline = tenant
   10909            1 :             .create_test_timeline_with_layers(
   10910            1 :                 TIMELINE_ID,
   10911            1 :                 baseline_image_layer_lsn,
   10912            1 :                 DEFAULT_PG_VERSION,
   10913            1 :                 &ctx,
   10914            1 :                 vec![open_layer, frozen_layer], // in-memory layers
   10915            1 :                 Vec::new(),                     // delta layers
   10916            1 :                 vec![
   10917            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10918            1 :                     (nested_image_layer_lsn, nested_img_layer),
   10919            1 :                 ], // image layers
   10920            1 :                 last_record_lsn,
   10921            1 :             )
   10922            1 :             .await?;
   10923            1 : 
   10924            1 :         let query = VersionedKeySpaceQuery::uniform(
   10925            1 :             KeySpace::single(get_key(0)..get_key(10)),
   10926            1 :             last_record_lsn,
   10927            1 :         );
   10928            1 : 
   10929            1 :         let results = tline
   10930            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   10931            1 :             .await
   10932            1 :             .expect("No vectored errors");
   10933           11 :         for (key, res) in results {
   10934           10 :             let value = res.expect("No key errors");
   10935           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10936           10 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   10937            1 : 
   10938           10 :             tracing::info!("key={key} value={expected_value}");
   10939            1 :         }
   10940            1 : 
   10941            1 :         Ok(())
   10942            1 :     }
   10943              : 
   10944              :     // A randomized read path test. Generates a layer map according to a deterministic
   10945              :     // specification. Fills the (key, LSN) space in random manner and then performs
   10946              :     // random scattered queries validating the results against in-memory storage.
   10947              :     //
   10948              :     // See this internal Notion page for a diagram of the layer map:
   10949              :     // https://www.notion.so/neondatabase/Read-Path-Unit-Testing-Fuzzing-1d1f189e0047806c8e5cd37781b0a350?pvs=4
   10950              :     //
   10951              :     // A fuzzing mode is also supported. In this mode, the test will use a random
   10952              :     // seed instead of a hardcoded one. Use it in conjunction with `cargo stress`
   10953              :     // to run multiple instances in parallel:
   10954              :     //
   10955              :     // $ RUST_BACKTRACE=1 RUST_LOG=INFO \
   10956              :     //   cargo stress --package=pageserver --features=testing,fuzz-read-path --release -- test_read_path
   10957              :     #[cfg(feature = "testing")]
   10958              :     #[tokio::test]
   10959            1 :     async fn test_read_path() -> anyhow::Result<()> {
   10960            1 :         use rand::seq::SliceRandom;
   10961            1 : 
   10962            1 :         let seed = if cfg!(feature = "fuzz-read-path") {
   10963            1 :             let seed: u64 = thread_rng().r#gen();
   10964            0 :             seed
   10965            1 :         } else {
   10966            1 :             // Use a hard-coded seed when not in fuzzing mode.
   10967            1 :             // Note that with the current approach results are not reproducible
   10968            1 :             // accross platforms and Rust releases.
   10969            1 :             const SEED: u64 = 0;
   10970            1 :             SEED
   10971            1 :         };
   10972            1 : 
   10973            1 :         let mut random = StdRng::seed_from_u64(seed);
   10974            1 : 
   10975            1 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   10976            1 :             const QUERIES: u64 = 5000;
   10977            1 :             let will_init_chance: u8 = random.gen_range(0..=10);
   10978            0 :             let gap_chance: u8 = random.gen_range(0..=50);
   10979            0 : 
   10980            0 :             (QUERIES, will_init_chance, gap_chance)
   10981            1 :         } else {
   10982            1 :             const QUERIES: u64 = 1000;
   10983            1 :             const WILL_INIT_CHANCE: u8 = 1;
   10984            1 :             const GAP_CHANCE: u8 = 5;
   10985            1 : 
   10986            1 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   10987            1 :         };
   10988            1 : 
   10989            1 :         let harness = TenantHarness::create("test_read_path").await?;
   10990            1 :         let (tenant, ctx) = harness.load().await;
   10991            1 : 
   10992            1 :         tracing::info!("Using random seed: {seed}");
   10993            1 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   10994            1 : 
   10995            1 :         // Define the layer map shape. Note that this part is not randomized.
   10996            1 : 
   10997            1 :         const KEY_DIMENSION_SIZE: u32 = 99;
   10998            1 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10999            1 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   11000            1 :         let total_key_range = start_key..end_key;
   11001            1 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   11002            1 :         let total_start_lsn = Lsn(104);
   11003            1 :         let last_record_lsn = Lsn(504);
   11004            1 : 
   11005            1 :         assert!(total_key_range_size % 3 == 0);
   11006            1 : 
   11007            1 :         let in_memory_layers_shape = vec![
   11008            1 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   11009            1 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   11010            1 :         ];
   11011            1 : 
   11012            1 :         let delta_layers_shape = vec![
   11013            1 :             (
   11014            1 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   11015            1 :                 Lsn(200)..Lsn(304),
   11016            1 :             ),
   11017            1 :             (
   11018            1 :                 (start_key.add((total_key_range_size / 3) as u32))
   11019            1 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   11020            1 :                 Lsn(200)..Lsn(304),
   11021            1 :             ),
   11022            1 :             (
   11023            1 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   11024            1 :                     ..(start_key.add(total_key_range_size as u32)),
   11025            1 :                 Lsn(200)..Lsn(304),
   11026            1 :             ),
   11027            1 :         ];
   11028            1 : 
   11029            1 :         let image_layers_shape = vec![
   11030            1 :             (
   11031            1 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   11032            1 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   11033            1 :                 Lsn(456),
   11034            1 :             ),
   11035            1 :             (
   11036            1 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   11037            1 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   11038            1 :                 Lsn(256),
   11039            1 :             ),
   11040            1 :             (total_key_range.clone(), total_start_lsn),
   11041            1 :         ];
   11042            1 : 
   11043            1 :         let specification = TestTimelineSpecification {
   11044            1 :             start_lsn: total_start_lsn,
   11045            1 :             last_record_lsn,
   11046            1 :             in_memory_layers_shape,
   11047            1 :             delta_layers_shape,
   11048            1 :             image_layers_shape,
   11049            1 :             gap_chance,
   11050            1 :             will_init_chance,
   11051            1 :         };
   11052            1 : 
   11053            1 :         // Create and randomly fill in the layers according to the specification
   11054            1 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   11055            1 :             &tenant,
   11056            1 :             TIMELINE_ID,
   11057            1 :             DEFAULT_PG_VERSION,
   11058            1 :             specification,
   11059            1 :             &mut random,
   11060            1 :             &ctx,
   11061            1 :         )
   11062            1 :         .await?;
   11063            1 : 
   11064            1 :         // Now generate queries based on the interesting lsns that we've collected.
   11065            1 :         //
   11066            1 :         // While there's still room in the query, pick and interesting LSN and a random
   11067            1 :         // key. Then roll the dice to see if the next key should also be included in
   11068            1 :         // the query. When the roll fails, break the "batch" and pick another point in the
   11069            1 :         // (key, LSN) space.
   11070            1 : 
   11071            1 :         const PICK_NEXT_CHANCE: u8 = 50;
   11072            1 :         for _ in 0..queries {
   11073         1000 :             let query = {
   11074         1000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   11075         1000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   11076            1 : 
   11077        22536 :                 while used_keys.len() < Timeline::MAX_GET_VECTORED_KEYS as usize {
   11078        21536 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11079        21536 :                     let mut selected_key = start_key.add(random.gen_range(0..KEY_DIMENSION_SIZE));
   11080            1 : 
   11081        37614 :                     while used_keys.len() < Timeline::MAX_GET_VECTORED_KEYS as usize {
   11082        37093 :                         if used_keys.contains(&selected_key)
   11083        32154 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11084            1 :                         {
   11085         5093 :                             break;
   11086        32000 :                         }
   11087        32000 : 
   11088        32000 :                         keyspaces_at_lsn
   11089        32000 :                             .entry(*selected_lsn)
   11090        32000 :                             .or_default()
   11091        32000 :                             .add_key(selected_key);
   11092        32000 :                         used_keys.insert(selected_key);
   11093        32000 : 
   11094        32000 :                         let pick_next = random.gen_range(0..=100) <= PICK_NEXT_CHANCE;
   11095        32000 :                         if pick_next {
   11096        16078 :                             selected_key = selected_key.next();
   11097        16078 :                         } else {
   11098        15922 :                             break;
   11099            1 :                         }
   11100            1 :                     }
   11101            1 :                 }
   11102            1 : 
   11103         1000 :                 VersionedKeySpaceQuery::scattered(
   11104         1000 :                     keyspaces_at_lsn
   11105         1000 :                         .into_iter()
   11106        11917 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11107         1000 :                         .collect(),
   11108         1000 :                 )
   11109            1 :             };
   11110            1 : 
   11111            1 :             // Run the query and validate the results
   11112            1 : 
   11113         1000 :             let results = tline
   11114         1000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11115         1000 :                 .await;
   11116            1 : 
   11117         1000 :             let blobs = match results {
   11118         1000 :                 Ok(ok) => ok,
   11119            1 :                 Err(err) => {
   11120            0 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11121            1 :                 }
   11122            1 :             };
   11123            1 : 
   11124        32000 :             for (key, key_res) in blobs.into_iter() {
   11125        32000 :                 match key_res {
   11126        32000 :                     Ok(blob) => {
   11127        32000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11128        32000 :                         let expected = storage.get(key, requested_at_lsn);
   11129        32000 : 
   11130        32000 :                         if blob != expected {
   11131            1 :                             tracing::error!(
   11132            1 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11133            1 :                             );
   11134        32000 :                         }
   11135            1 : 
   11136        32000 :                         assert_eq!(blob, expected);
   11137            1 :                     }
   11138            1 :                     Err(err) => {
   11139            0 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11140            0 : 
   11141            0 :                         panic!(
   11142            0 :                             "seed={seed} Error returned for {key}@{requested_at_lsn} from query {query}: {err}"
   11143            0 :                         );
   11144            1 :                     }
   11145            1 :                 }
   11146            1 :             }
   11147            1 :         }
   11148            1 : 
   11149            1 :         Ok(())
   11150            1 :     }
   11151              : 
   11152          107 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11153          107 :         (
   11154          107 :             k1.is_delta,
   11155          107 :             k1.key_range.start,
   11156          107 :             k1.key_range.end,
   11157          107 :             k1.lsn_range.start,
   11158          107 :             k1.lsn_range.end,
   11159          107 :         )
   11160          107 :             .cmp(&(
   11161          107 :                 k2.is_delta,
   11162          107 :                 k2.key_range.start,
   11163          107 :                 k2.key_range.end,
   11164          107 :                 k2.lsn_range.start,
   11165          107 :                 k2.lsn_range.end,
   11166          107 :             ))
   11167          107 :     }
   11168              : 
   11169           12 :     async fn inspect_and_sort(
   11170           12 :         tline: &Arc<Timeline>,
   11171           12 :         filter: Option<std::ops::Range<Key>>,
   11172           12 :     ) -> Vec<PersistentLayerKey> {
   11173           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11174           12 :         if let Some(filter) = filter {
   11175           54 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11176           11 :         }
   11177           12 :         all_layers.sort_by(sort_layer_key);
   11178           12 :         all_layers
   11179           12 :     }
   11180              : 
   11181              :     #[cfg(feature = "testing")]
   11182           11 :     fn check_layer_map_key_eq(
   11183           11 :         mut left: Vec<PersistentLayerKey>,
   11184           11 :         mut right: Vec<PersistentLayerKey>,
   11185           11 :     ) {
   11186           11 :         left.sort_by(sort_layer_key);
   11187           11 :         right.sort_by(sort_layer_key);
   11188           11 :         if left != right {
   11189            0 :             eprintln!("---LEFT---");
   11190            0 :             for left in left.iter() {
   11191            0 :                 eprintln!("{}", left);
   11192            0 :             }
   11193            0 :             eprintln!("---RIGHT---");
   11194            0 :             for right in right.iter() {
   11195            0 :                 eprintln!("{}", right);
   11196            0 :             }
   11197            0 :             assert_eq!(left, right);
   11198           11 :         }
   11199           11 :     }
   11200              : 
   11201              :     #[cfg(feature = "testing")]
   11202              :     #[tokio::test]
   11203            1 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11204            1 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11205            1 :         let (tenant, ctx) = harness.load().await;
   11206            1 : 
   11207           91 :         fn get_key(id: u32) -> Key {
   11208           91 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11209           91 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11210           91 :             key.field6 = id;
   11211           91 :             key
   11212           91 :         }
   11213            1 : 
   11214            1 :         // img layer at 0x10
   11215            1 :         let img_layer = (0..10)
   11216           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11217            1 :             .collect_vec();
   11218            1 : 
   11219            1 :         let delta1 = vec![
   11220            1 :             (
   11221            1 :                 get_key(1),
   11222            1 :                 Lsn(0x20),
   11223            1 :                 Value::Image(Bytes::from("value 1@0x20")),
   11224            1 :             ),
   11225            1 :             (
   11226            1 :                 get_key(2),
   11227            1 :                 Lsn(0x30),
   11228            1 :                 Value::Image(Bytes::from("value 2@0x30")),
   11229            1 :             ),
   11230            1 :             (
   11231            1 :                 get_key(3),
   11232            1 :                 Lsn(0x40),
   11233            1 :                 Value::Image(Bytes::from("value 3@0x40")),
   11234            1 :             ),
   11235            1 :         ];
   11236            1 :         let delta2 = vec![
   11237            1 :             (
   11238            1 :                 get_key(5),
   11239            1 :                 Lsn(0x20),
   11240            1 :                 Value::Image(Bytes::from("value 5@0x20")),
   11241            1 :             ),
   11242            1 :             (
   11243            1 :                 get_key(6),
   11244            1 :                 Lsn(0x20),
   11245            1 :                 Value::Image(Bytes::from("value 6@0x20")),
   11246            1 :             ),
   11247            1 :         ];
   11248            1 :         let delta3 = vec![
   11249            1 :             (
   11250            1 :                 get_key(8),
   11251            1 :                 Lsn(0x48),
   11252            1 :                 Value::Image(Bytes::from("value 8@0x48")),
   11253            1 :             ),
   11254            1 :             (
   11255            1 :                 get_key(9),
   11256            1 :                 Lsn(0x48),
   11257            1 :                 Value::Image(Bytes::from("value 9@0x48")),
   11258            1 :             ),
   11259            1 :         ];
   11260            1 : 
   11261            1 :         let tline = tenant
   11262            1 :             .create_test_timeline_with_layers(
   11263            1 :                 TIMELINE_ID,
   11264            1 :                 Lsn(0x10),
   11265            1 :                 DEFAULT_PG_VERSION,
   11266            1 :                 &ctx,
   11267            1 :                 vec![], // in-memory layers
   11268            1 :                 vec![
   11269            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11270            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11271            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11272            1 :                 ], // delta layers
   11273            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11274            1 :                 Lsn(0x50),
   11275            1 :             )
   11276            1 :             .await?;
   11277            1 : 
   11278            1 :         {
   11279            1 :             tline
   11280            1 :                 .applied_gc_cutoff_lsn
   11281            1 :                 .lock_for_write()
   11282            1 :                 .store_and_unlock(Lsn(0x30))
   11283            1 :                 .wait()
   11284            1 :                 .await;
   11285            1 :             // Update GC info
   11286            1 :             let mut guard = tline.gc_info.write().unwrap();
   11287            1 :             *guard = GcInfo {
   11288            1 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11289            1 :                 cutoffs: GcCutoffs {
   11290            1 :                     time: Some(Lsn(0x30)),
   11291            1 :                     space: Lsn(0x30),
   11292            1 :                 },
   11293            1 :                 leases: Default::default(),
   11294            1 :                 within_ancestor_pitr: false,
   11295            1 :             };
   11296            1 :         }
   11297            1 : 
   11298            1 :         let cancel = CancellationToken::new();
   11299            1 : 
   11300            1 :         // Do a partial compaction on key range 0..2
   11301            1 :         tline
   11302            1 :             .compact_with_gc(
   11303            1 :                 &cancel,
   11304            1 :                 CompactOptions {
   11305            1 :                     flags: EnumSet::new(),
   11306            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11307            1 :                     ..Default::default()
   11308            1 :                 },
   11309            1 :                 &ctx,
   11310            1 :             )
   11311            1 :             .await
   11312            1 :             .unwrap();
   11313            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11314            1 :         check_layer_map_key_eq(
   11315            1 :             all_layers,
   11316            1 :             vec![
   11317            1 :                 // newly-generated image layer for the partial compaction range 0-2
   11318            1 :                 PersistentLayerKey {
   11319            1 :                     key_range: get_key(0)..get_key(2),
   11320            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11321            1 :                     is_delta: false,
   11322            1 :                 },
   11323            1 :                 PersistentLayerKey {
   11324            1 :                     key_range: get_key(0)..get_key(10),
   11325            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11326            1 :                     is_delta: false,
   11327            1 :                 },
   11328            1 :                 // delta1 is split and the second part is rewritten
   11329            1 :                 PersistentLayerKey {
   11330            1 :                     key_range: get_key(2)..get_key(4),
   11331            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11332            1 :                     is_delta: true,
   11333            1 :                 },
   11334            1 :                 PersistentLayerKey {
   11335            1 :                     key_range: get_key(5)..get_key(7),
   11336            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11337            1 :                     is_delta: true,
   11338            1 :                 },
   11339            1 :                 PersistentLayerKey {
   11340            1 :                     key_range: get_key(8)..get_key(10),
   11341            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11342            1 :                     is_delta: true,
   11343            1 :                 },
   11344            1 :             ],
   11345            1 :         );
   11346            1 : 
   11347            1 :         // Do a partial compaction on key range 2..4
   11348            1 :         tline
   11349            1 :             .compact_with_gc(
   11350            1 :                 &cancel,
   11351            1 :                 CompactOptions {
   11352            1 :                     flags: EnumSet::new(),
   11353            1 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11354            1 :                     ..Default::default()
   11355            1 :                 },
   11356            1 :                 &ctx,
   11357            1 :             )
   11358            1 :             .await
   11359            1 :             .unwrap();
   11360            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11361            1 :         check_layer_map_key_eq(
   11362            1 :             all_layers,
   11363            1 :             vec![
   11364            1 :                 PersistentLayerKey {
   11365            1 :                     key_range: get_key(0)..get_key(2),
   11366            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11367            1 :                     is_delta: false,
   11368            1 :                 },
   11369            1 :                 PersistentLayerKey {
   11370            1 :                     key_range: get_key(0)..get_key(10),
   11371            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11372            1 :                     is_delta: false,
   11373            1 :                 },
   11374            1 :                 // image layer generated for the compaction range 2-4
   11375            1 :                 PersistentLayerKey {
   11376            1 :                     key_range: get_key(2)..get_key(4),
   11377            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11378            1 :                     is_delta: false,
   11379            1 :                 },
   11380            1 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11381            1 :                 PersistentLayerKey {
   11382            1 :                     key_range: get_key(2)..get_key(4),
   11383            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11384            1 :                     is_delta: true,
   11385            1 :                 },
   11386            1 :                 PersistentLayerKey {
   11387            1 :                     key_range: get_key(5)..get_key(7),
   11388            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11389            1 :                     is_delta: true,
   11390            1 :                 },
   11391            1 :                 PersistentLayerKey {
   11392            1 :                     key_range: get_key(8)..get_key(10),
   11393            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11394            1 :                     is_delta: true,
   11395            1 :                 },
   11396            1 :             ],
   11397            1 :         );
   11398            1 : 
   11399            1 :         // Do a partial compaction on key range 4..9
   11400            1 :         tline
   11401            1 :             .compact_with_gc(
   11402            1 :                 &cancel,
   11403            1 :                 CompactOptions {
   11404            1 :                     flags: EnumSet::new(),
   11405            1 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11406            1 :                     ..Default::default()
   11407            1 :                 },
   11408            1 :                 &ctx,
   11409            1 :             )
   11410            1 :             .await
   11411            1 :             .unwrap();
   11412            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11413            1 :         check_layer_map_key_eq(
   11414            1 :             all_layers,
   11415            1 :             vec![
   11416            1 :                 PersistentLayerKey {
   11417            1 :                     key_range: get_key(0)..get_key(2),
   11418            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11419            1 :                     is_delta: false,
   11420            1 :                 },
   11421            1 :                 PersistentLayerKey {
   11422            1 :                     key_range: get_key(0)..get_key(10),
   11423            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11424            1 :                     is_delta: false,
   11425            1 :                 },
   11426            1 :                 PersistentLayerKey {
   11427            1 :                     key_range: get_key(2)..get_key(4),
   11428            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11429            1 :                     is_delta: false,
   11430            1 :                 },
   11431            1 :                 PersistentLayerKey {
   11432            1 :                     key_range: get_key(2)..get_key(4),
   11433            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11434            1 :                     is_delta: true,
   11435            1 :                 },
   11436            1 :                 // image layer generated for this compaction range
   11437            1 :                 PersistentLayerKey {
   11438            1 :                     key_range: get_key(4)..get_key(9),
   11439            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11440            1 :                     is_delta: false,
   11441            1 :                 },
   11442            1 :                 PersistentLayerKey {
   11443            1 :                     key_range: get_key(8)..get_key(10),
   11444            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11445            1 :                     is_delta: true,
   11446            1 :                 },
   11447            1 :             ],
   11448            1 :         );
   11449            1 : 
   11450            1 :         // Do a partial compaction on key range 9..10
   11451            1 :         tline
   11452            1 :             .compact_with_gc(
   11453            1 :                 &cancel,
   11454            1 :                 CompactOptions {
   11455            1 :                     flags: EnumSet::new(),
   11456            1 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11457            1 :                     ..Default::default()
   11458            1 :                 },
   11459            1 :                 &ctx,
   11460            1 :             )
   11461            1 :             .await
   11462            1 :             .unwrap();
   11463            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11464            1 :         check_layer_map_key_eq(
   11465            1 :             all_layers,
   11466            1 :             vec![
   11467            1 :                 PersistentLayerKey {
   11468            1 :                     key_range: get_key(0)..get_key(2),
   11469            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11470            1 :                     is_delta: false,
   11471            1 :                 },
   11472            1 :                 PersistentLayerKey {
   11473            1 :                     key_range: get_key(0)..get_key(10),
   11474            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11475            1 :                     is_delta: false,
   11476            1 :                 },
   11477            1 :                 PersistentLayerKey {
   11478            1 :                     key_range: get_key(2)..get_key(4),
   11479            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11480            1 :                     is_delta: false,
   11481            1 :                 },
   11482            1 :                 PersistentLayerKey {
   11483            1 :                     key_range: get_key(2)..get_key(4),
   11484            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11485            1 :                     is_delta: true,
   11486            1 :                 },
   11487            1 :                 PersistentLayerKey {
   11488            1 :                     key_range: get_key(4)..get_key(9),
   11489            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11490            1 :                     is_delta: false,
   11491            1 :                 },
   11492            1 :                 // image layer generated for the compaction range
   11493            1 :                 PersistentLayerKey {
   11494            1 :                     key_range: get_key(9)..get_key(10),
   11495            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11496            1 :                     is_delta: false,
   11497            1 :                 },
   11498            1 :                 PersistentLayerKey {
   11499            1 :                     key_range: get_key(8)..get_key(10),
   11500            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11501            1 :                     is_delta: true,
   11502            1 :                 },
   11503            1 :             ],
   11504            1 :         );
   11505            1 : 
   11506            1 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11507            1 :         tline
   11508            1 :             .compact_with_gc(
   11509            1 :                 &cancel,
   11510            1 :                 CompactOptions {
   11511            1 :                     flags: EnumSet::new(),
   11512            1 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11513            1 :                     ..Default::default()
   11514            1 :                 },
   11515            1 :                 &ctx,
   11516            1 :             )
   11517            1 :             .await
   11518            1 :             .unwrap();
   11519            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11520            1 :         check_layer_map_key_eq(
   11521            1 :             all_layers,
   11522            1 :             vec![
   11523            1 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11524            1 :                 PersistentLayerKey {
   11525            1 :                     key_range: get_key(0)..get_key(10),
   11526            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11527            1 :                     is_delta: false,
   11528            1 :                 },
   11529            1 :                 PersistentLayerKey {
   11530            1 :                     key_range: get_key(2)..get_key(4),
   11531            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11532            1 :                     is_delta: true,
   11533            1 :                 },
   11534            1 :                 PersistentLayerKey {
   11535            1 :                     key_range: get_key(8)..get_key(10),
   11536            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11537            1 :                     is_delta: true,
   11538            1 :                 },
   11539            1 :             ],
   11540            1 :         );
   11541            1 :         Ok(())
   11542            1 :     }
   11543              : 
   11544              :     #[cfg(feature = "testing")]
   11545              :     #[tokio::test]
   11546            1 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11547            1 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11548            1 :             .await
   11549            1 :             .unwrap();
   11550            1 :         let (tenant, ctx) = harness.load().await;
   11551            1 :         let tline_parent = tenant
   11552            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11553            1 :             .await
   11554            1 :             .unwrap();
   11555            1 :         let tline_child = tenant
   11556            1 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11557            1 :             .await
   11558            1 :             .unwrap();
   11559            1 :         {
   11560            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11561            1 :             assert_eq!(
   11562            1 :                 gc_info_parent.retain_lsns,
   11563            1 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11564            1 :             );
   11565            1 :         }
   11566            1 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11567            1 :         tline_child
   11568            1 :             .remote_client
   11569            1 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11570            1 :             .unwrap();
   11571            1 :         tline_child.remote_client.wait_completion().await.unwrap();
   11572            1 :         offload_timeline(&tenant, &tline_child)
   11573            1 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11574            1 :             .await.unwrap();
   11575            1 :         let child_timeline_id = tline_child.timeline_id;
   11576            1 :         Arc::try_unwrap(tline_child).unwrap();
   11577            1 : 
   11578            1 :         {
   11579            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11580            1 :             assert_eq!(
   11581            1 :                 gc_info_parent.retain_lsns,
   11582            1 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11583            1 :             );
   11584            1 :         }
   11585            1 : 
   11586            1 :         tenant
   11587            1 :             .get_offloaded_timeline(child_timeline_id)
   11588            1 :             .unwrap()
   11589            1 :             .defuse_for_tenant_drop();
   11590            1 : 
   11591            1 :         Ok(())
   11592            1 :     }
   11593              : 
   11594              :     #[cfg(feature = "testing")]
   11595              :     #[tokio::test]
   11596            1 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11597            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11598            1 :         let (tenant, ctx) = harness.load().await;
   11599            1 : 
   11600          148 :         fn get_key(id: u32) -> Key {
   11601          148 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11602          148 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11603          148 :             key.field6 = id;
   11604          148 :             key
   11605          148 :         }
   11606            1 : 
   11607            1 :         let img_layer = (0..10)
   11608           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11609            1 :             .collect_vec();
   11610            1 : 
   11611            1 :         let delta1 = vec![(
   11612            1 :             get_key(1),
   11613            1 :             Lsn(0x20),
   11614            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11615            1 :         )];
   11616            1 :         let delta4 = vec![(
   11617            1 :             get_key(1),
   11618            1 :             Lsn(0x28),
   11619            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11620            1 :         )];
   11621            1 :         let delta2 = vec![
   11622            1 :             (
   11623            1 :                 get_key(1),
   11624            1 :                 Lsn(0x30),
   11625            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11626            1 :             ),
   11627            1 :             (
   11628            1 :                 get_key(1),
   11629            1 :                 Lsn(0x38),
   11630            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11631            1 :             ),
   11632            1 :         ];
   11633            1 :         let delta3 = vec![
   11634            1 :             (
   11635            1 :                 get_key(8),
   11636            1 :                 Lsn(0x48),
   11637            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11638            1 :             ),
   11639            1 :             (
   11640            1 :                 get_key(9),
   11641            1 :                 Lsn(0x48),
   11642            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11643            1 :             ),
   11644            1 :         ];
   11645            1 : 
   11646            1 :         let tline = tenant
   11647            1 :             .create_test_timeline_with_layers(
   11648            1 :                 TIMELINE_ID,
   11649            1 :                 Lsn(0x10),
   11650            1 :                 DEFAULT_PG_VERSION,
   11651            1 :                 &ctx,
   11652            1 :                 vec![], // in-memory layers
   11653            1 :                 vec![
   11654            1 :                     // delta1/2/4 only contain a single key but multiple updates
   11655            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11656            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11657            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11658            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11659            1 :                 ], // delta layers
   11660            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11661            1 :                 Lsn(0x50),
   11662            1 :             )
   11663            1 :             .await?;
   11664            1 :         {
   11665            1 :             tline
   11666            1 :                 .applied_gc_cutoff_lsn
   11667            1 :                 .lock_for_write()
   11668            1 :                 .store_and_unlock(Lsn(0x30))
   11669            1 :                 .wait()
   11670            1 :                 .await;
   11671            1 :             // Update GC info
   11672            1 :             let mut guard = tline.gc_info.write().unwrap();
   11673            1 :             *guard = GcInfo {
   11674            1 :                 retain_lsns: vec![
   11675            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11676            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11677            1 :                 ],
   11678            1 :                 cutoffs: GcCutoffs {
   11679            1 :                     time: Some(Lsn(0x30)),
   11680            1 :                     space: Lsn(0x30),
   11681            1 :                 },
   11682            1 :                 leases: Default::default(),
   11683            1 :                 within_ancestor_pitr: false,
   11684            1 :             };
   11685            1 :         }
   11686            1 : 
   11687            1 :         let expected_result = [
   11688            1 :             Bytes::from_static(b"value 0@0x10"),
   11689            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11690            1 :             Bytes::from_static(b"value 2@0x10"),
   11691            1 :             Bytes::from_static(b"value 3@0x10"),
   11692            1 :             Bytes::from_static(b"value 4@0x10"),
   11693            1 :             Bytes::from_static(b"value 5@0x10"),
   11694            1 :             Bytes::from_static(b"value 6@0x10"),
   11695            1 :             Bytes::from_static(b"value 7@0x10"),
   11696            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11697            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11698            1 :         ];
   11699            1 : 
   11700            1 :         let expected_result_at_gc_horizon = [
   11701            1 :             Bytes::from_static(b"value 0@0x10"),
   11702            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11703            1 :             Bytes::from_static(b"value 2@0x10"),
   11704            1 :             Bytes::from_static(b"value 3@0x10"),
   11705            1 :             Bytes::from_static(b"value 4@0x10"),
   11706            1 :             Bytes::from_static(b"value 5@0x10"),
   11707            1 :             Bytes::from_static(b"value 6@0x10"),
   11708            1 :             Bytes::from_static(b"value 7@0x10"),
   11709            1 :             Bytes::from_static(b"value 8@0x10"),
   11710            1 :             Bytes::from_static(b"value 9@0x10"),
   11711            1 :         ];
   11712            1 : 
   11713            1 :         let expected_result_at_lsn_20 = [
   11714            1 :             Bytes::from_static(b"value 0@0x10"),
   11715            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11716            1 :             Bytes::from_static(b"value 2@0x10"),
   11717            1 :             Bytes::from_static(b"value 3@0x10"),
   11718            1 :             Bytes::from_static(b"value 4@0x10"),
   11719            1 :             Bytes::from_static(b"value 5@0x10"),
   11720            1 :             Bytes::from_static(b"value 6@0x10"),
   11721            1 :             Bytes::from_static(b"value 7@0x10"),
   11722            1 :             Bytes::from_static(b"value 8@0x10"),
   11723            1 :             Bytes::from_static(b"value 9@0x10"),
   11724            1 :         ];
   11725            1 : 
   11726            1 :         let expected_result_at_lsn_10 = [
   11727            1 :             Bytes::from_static(b"value 0@0x10"),
   11728            1 :             Bytes::from_static(b"value 1@0x10"),
   11729            1 :             Bytes::from_static(b"value 2@0x10"),
   11730            1 :             Bytes::from_static(b"value 3@0x10"),
   11731            1 :             Bytes::from_static(b"value 4@0x10"),
   11732            1 :             Bytes::from_static(b"value 5@0x10"),
   11733            1 :             Bytes::from_static(b"value 6@0x10"),
   11734            1 :             Bytes::from_static(b"value 7@0x10"),
   11735            1 :             Bytes::from_static(b"value 8@0x10"),
   11736            1 :             Bytes::from_static(b"value 9@0x10"),
   11737            1 :         ];
   11738            1 : 
   11739            3 :         let verify_result = || async {
   11740            3 :             let gc_horizon = {
   11741            3 :                 let gc_info = tline.gc_info.read().unwrap();
   11742            3 :                 gc_info.cutoffs.time.unwrap_or_default()
   11743            1 :             };
   11744           33 :             for idx in 0..10 {
   11745           30 :                 assert_eq!(
   11746           30 :                     tline
   11747           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11748           30 :                         .await
   11749           30 :                         .unwrap(),
   11750           30 :                     &expected_result[idx]
   11751            1 :                 );
   11752           30 :                 assert_eq!(
   11753           30 :                     tline
   11754           30 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11755           30 :                         .await
   11756           30 :                         .unwrap(),
   11757           30 :                     &expected_result_at_gc_horizon[idx]
   11758            1 :                 );
   11759           30 :                 assert_eq!(
   11760           30 :                     tline
   11761           30 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11762           30 :                         .await
   11763           30 :                         .unwrap(),
   11764           30 :                     &expected_result_at_lsn_20[idx]
   11765            1 :                 );
   11766           30 :                 assert_eq!(
   11767           30 :                     tline
   11768           30 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11769           30 :                         .await
   11770           30 :                         .unwrap(),
   11771           30 :                     &expected_result_at_lsn_10[idx]
   11772            1 :                 );
   11773            1 :             }
   11774            6 :         };
   11775            1 : 
   11776            1 :         verify_result().await;
   11777            1 : 
   11778            1 :         let cancel = CancellationToken::new();
   11779            1 :         tline
   11780            1 :             .compact_with_gc(
   11781            1 :                 &cancel,
   11782            1 :                 CompactOptions {
   11783            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   11784            1 :                     ..Default::default()
   11785            1 :                 },
   11786            1 :                 &ctx,
   11787            1 :             )
   11788            1 :             .await
   11789            1 :             .unwrap();
   11790            1 :         verify_result().await;
   11791            1 : 
   11792            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11793            1 :         check_layer_map_key_eq(
   11794            1 :             all_layers,
   11795            1 :             vec![
   11796            1 :                 // The original image layer, not compacted
   11797            1 :                 PersistentLayerKey {
   11798            1 :                     key_range: get_key(0)..get_key(10),
   11799            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11800            1 :                     is_delta: false,
   11801            1 :                 },
   11802            1 :                 // Delta layer below the specified above_lsn not compacted
   11803            1 :                 PersistentLayerKey {
   11804            1 :                     key_range: get_key(1)..get_key(2),
   11805            1 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   11806            1 :                     is_delta: true,
   11807            1 :                 },
   11808            1 :                 // Delta layer compacted above the LSN
   11809            1 :                 PersistentLayerKey {
   11810            1 :                     key_range: get_key(1)..get_key(10),
   11811            1 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   11812            1 :                     is_delta: true,
   11813            1 :                 },
   11814            1 :             ],
   11815            1 :         );
   11816            1 : 
   11817            1 :         // compact again
   11818            1 :         tline
   11819            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11820            1 :             .await
   11821            1 :             .unwrap();
   11822            1 :         verify_result().await;
   11823            1 : 
   11824            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11825            1 :         check_layer_map_key_eq(
   11826            1 :             all_layers,
   11827            1 :             vec![
   11828            1 :                 // The compacted image layer (full key range)
   11829            1 :                 PersistentLayerKey {
   11830            1 :                     key_range: Key::MIN..Key::MAX,
   11831            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11832            1 :                     is_delta: false,
   11833            1 :                 },
   11834            1 :                 // All other data in the delta layer
   11835            1 :                 PersistentLayerKey {
   11836            1 :                     key_range: get_key(1)..get_key(10),
   11837            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11838            1 :                     is_delta: true,
   11839            1 :                 },
   11840            1 :             ],
   11841            1 :         );
   11842            1 : 
   11843            1 :         Ok(())
   11844            1 :     }
   11845              : 
   11846              :     #[cfg(feature = "testing")]
   11847              :     #[tokio::test]
   11848            1 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   11849            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   11850            1 :         let (tenant, ctx) = harness.load().await;
   11851            1 : 
   11852          254 :         fn get_key(id: u32) -> Key {
   11853          254 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11854          254 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11855          254 :             key.field6 = id;
   11856          254 :             key
   11857          254 :         }
   11858            1 : 
   11859            1 :         let img_layer = (0..10)
   11860           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11861            1 :             .collect_vec();
   11862            1 : 
   11863            1 :         let delta1 = vec![(
   11864            1 :             get_key(1),
   11865            1 :             Lsn(0x20),
   11866            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11867            1 :         )];
   11868            1 :         let delta4 = vec![(
   11869            1 :             get_key(1),
   11870            1 :             Lsn(0x28),
   11871            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11872            1 :         )];
   11873            1 :         let delta2 = vec![
   11874            1 :             (
   11875            1 :                 get_key(1),
   11876            1 :                 Lsn(0x30),
   11877            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11878            1 :             ),
   11879            1 :             (
   11880            1 :                 get_key(1),
   11881            1 :                 Lsn(0x38),
   11882            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11883            1 :             ),
   11884            1 :         ];
   11885            1 :         let delta3 = vec![
   11886            1 :             (
   11887            1 :                 get_key(8),
   11888            1 :                 Lsn(0x48),
   11889            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11890            1 :             ),
   11891            1 :             (
   11892            1 :                 get_key(9),
   11893            1 :                 Lsn(0x48),
   11894            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11895            1 :             ),
   11896            1 :         ];
   11897            1 : 
   11898            1 :         let tline = tenant
   11899            1 :             .create_test_timeline_with_layers(
   11900            1 :                 TIMELINE_ID,
   11901            1 :                 Lsn(0x10),
   11902            1 :                 DEFAULT_PG_VERSION,
   11903            1 :                 &ctx,
   11904            1 :                 vec![], // in-memory layers
   11905            1 :                 vec![
   11906            1 :                     // delta1/2/4 only contain a single key but multiple updates
   11907            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11908            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11909            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11910            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11911            1 :                 ], // delta layers
   11912            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11913            1 :                 Lsn(0x50),
   11914            1 :             )
   11915            1 :             .await?;
   11916            1 :         {
   11917            1 :             tline
   11918            1 :                 .applied_gc_cutoff_lsn
   11919            1 :                 .lock_for_write()
   11920            1 :                 .store_and_unlock(Lsn(0x30))
   11921            1 :                 .wait()
   11922            1 :                 .await;
   11923            1 :             // Update GC info
   11924            1 :             let mut guard = tline.gc_info.write().unwrap();
   11925            1 :             *guard = GcInfo {
   11926            1 :                 retain_lsns: vec![
   11927            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11928            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11929            1 :                 ],
   11930            1 :                 cutoffs: GcCutoffs {
   11931            1 :                     time: Some(Lsn(0x30)),
   11932            1 :                     space: Lsn(0x30),
   11933            1 :                 },
   11934            1 :                 leases: Default::default(),
   11935            1 :                 within_ancestor_pitr: false,
   11936            1 :             };
   11937            1 :         }
   11938            1 : 
   11939            1 :         let expected_result = [
   11940            1 :             Bytes::from_static(b"value 0@0x10"),
   11941            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11942            1 :             Bytes::from_static(b"value 2@0x10"),
   11943            1 :             Bytes::from_static(b"value 3@0x10"),
   11944            1 :             Bytes::from_static(b"value 4@0x10"),
   11945            1 :             Bytes::from_static(b"value 5@0x10"),
   11946            1 :             Bytes::from_static(b"value 6@0x10"),
   11947            1 :             Bytes::from_static(b"value 7@0x10"),
   11948            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11949            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11950            1 :         ];
   11951            1 : 
   11952            1 :         let expected_result_at_gc_horizon = [
   11953            1 :             Bytes::from_static(b"value 0@0x10"),
   11954            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11955            1 :             Bytes::from_static(b"value 2@0x10"),
   11956            1 :             Bytes::from_static(b"value 3@0x10"),
   11957            1 :             Bytes::from_static(b"value 4@0x10"),
   11958            1 :             Bytes::from_static(b"value 5@0x10"),
   11959            1 :             Bytes::from_static(b"value 6@0x10"),
   11960            1 :             Bytes::from_static(b"value 7@0x10"),
   11961            1 :             Bytes::from_static(b"value 8@0x10"),
   11962            1 :             Bytes::from_static(b"value 9@0x10"),
   11963            1 :         ];
   11964            1 : 
   11965            1 :         let expected_result_at_lsn_20 = [
   11966            1 :             Bytes::from_static(b"value 0@0x10"),
   11967            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11968            1 :             Bytes::from_static(b"value 2@0x10"),
   11969            1 :             Bytes::from_static(b"value 3@0x10"),
   11970            1 :             Bytes::from_static(b"value 4@0x10"),
   11971            1 :             Bytes::from_static(b"value 5@0x10"),
   11972            1 :             Bytes::from_static(b"value 6@0x10"),
   11973            1 :             Bytes::from_static(b"value 7@0x10"),
   11974            1 :             Bytes::from_static(b"value 8@0x10"),
   11975            1 :             Bytes::from_static(b"value 9@0x10"),
   11976            1 :         ];
   11977            1 : 
   11978            1 :         let expected_result_at_lsn_10 = [
   11979            1 :             Bytes::from_static(b"value 0@0x10"),
   11980            1 :             Bytes::from_static(b"value 1@0x10"),
   11981            1 :             Bytes::from_static(b"value 2@0x10"),
   11982            1 :             Bytes::from_static(b"value 3@0x10"),
   11983            1 :             Bytes::from_static(b"value 4@0x10"),
   11984            1 :             Bytes::from_static(b"value 5@0x10"),
   11985            1 :             Bytes::from_static(b"value 6@0x10"),
   11986            1 :             Bytes::from_static(b"value 7@0x10"),
   11987            1 :             Bytes::from_static(b"value 8@0x10"),
   11988            1 :             Bytes::from_static(b"value 9@0x10"),
   11989            1 :         ];
   11990            1 : 
   11991            5 :         let verify_result = || async {
   11992            5 :             let gc_horizon = {
   11993            5 :                 let gc_info = tline.gc_info.read().unwrap();
   11994            5 :                 gc_info.cutoffs.time.unwrap_or_default()
   11995            1 :             };
   11996           55 :             for idx in 0..10 {
   11997           50 :                 assert_eq!(
   11998           50 :                     tline
   11999           50 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12000           50 :                         .await
   12001           50 :                         .unwrap(),
   12002           50 :                     &expected_result[idx]
   12003            1 :                 );
   12004           50 :                 assert_eq!(
   12005           50 :                     tline
   12006           50 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12007           50 :                         .await
   12008           50 :                         .unwrap(),
   12009           50 :                     &expected_result_at_gc_horizon[idx]
   12010            1 :                 );
   12011           50 :                 assert_eq!(
   12012           50 :                     tline
   12013           50 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12014           50 :                         .await
   12015           50 :                         .unwrap(),
   12016           50 :                     &expected_result_at_lsn_20[idx]
   12017            1 :                 );
   12018           50 :                 assert_eq!(
   12019           50 :                     tline
   12020           50 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12021           50 :                         .await
   12022           50 :                         .unwrap(),
   12023           50 :                     &expected_result_at_lsn_10[idx]
   12024            1 :                 );
   12025            1 :             }
   12026           10 :         };
   12027            1 : 
   12028            1 :         verify_result().await;
   12029            1 : 
   12030            1 :         let cancel = CancellationToken::new();
   12031            1 : 
   12032            1 :         tline
   12033            1 :             .compact_with_gc(
   12034            1 :                 &cancel,
   12035            1 :                 CompactOptions {
   12036            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   12037            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   12038            1 :                     ..Default::default()
   12039            1 :                 },
   12040            1 :                 &ctx,
   12041            1 :             )
   12042            1 :             .await
   12043            1 :             .unwrap();
   12044            1 :         verify_result().await;
   12045            1 : 
   12046            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12047            1 :         check_layer_map_key_eq(
   12048            1 :             all_layers,
   12049            1 :             vec![
   12050            1 :                 // The original image layer, not compacted
   12051            1 :                 PersistentLayerKey {
   12052            1 :                     key_range: get_key(0)..get_key(10),
   12053            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12054            1 :                     is_delta: false,
   12055            1 :                 },
   12056            1 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   12057            1 :                 // the layer 0x28-0x30 into one.
   12058            1 :                 PersistentLayerKey {
   12059            1 :                     key_range: get_key(1)..get_key(2),
   12060            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12061            1 :                     is_delta: true,
   12062            1 :                 },
   12063            1 :                 // Above the upper bound and untouched
   12064            1 :                 PersistentLayerKey {
   12065            1 :                     key_range: get_key(1)..get_key(2),
   12066            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12067            1 :                     is_delta: true,
   12068            1 :                 },
   12069            1 :                 // This layer is untouched
   12070            1 :                 PersistentLayerKey {
   12071            1 :                     key_range: get_key(8)..get_key(10),
   12072            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12073            1 :                     is_delta: true,
   12074            1 :                 },
   12075            1 :             ],
   12076            1 :         );
   12077            1 : 
   12078            1 :         tline
   12079            1 :             .compact_with_gc(
   12080            1 :                 &cancel,
   12081            1 :                 CompactOptions {
   12082            1 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12083            1 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12084            1 :                     ..Default::default()
   12085            1 :                 },
   12086            1 :                 &ctx,
   12087            1 :             )
   12088            1 :             .await
   12089            1 :             .unwrap();
   12090            1 :         verify_result().await;
   12091            1 : 
   12092            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12093            1 :         check_layer_map_key_eq(
   12094            1 :             all_layers,
   12095            1 :             vec![
   12096            1 :                 // The original image layer, not compacted
   12097            1 :                 PersistentLayerKey {
   12098            1 :                     key_range: get_key(0)..get_key(10),
   12099            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12100            1 :                     is_delta: false,
   12101            1 :                 },
   12102            1 :                 // Not in the compaction key range, uncompacted
   12103            1 :                 PersistentLayerKey {
   12104            1 :                     key_range: get_key(1)..get_key(2),
   12105            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12106            1 :                     is_delta: true,
   12107            1 :                 },
   12108            1 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12109            1 :                 PersistentLayerKey {
   12110            1 :                     key_range: get_key(1)..get_key(2),
   12111            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12112            1 :                     is_delta: true,
   12113            1 :                 },
   12114            1 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12115            1 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12116            1 :                 // becomes 0x50.
   12117            1 :                 PersistentLayerKey {
   12118            1 :                     key_range: get_key(8)..get_key(10),
   12119            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12120            1 :                     is_delta: true,
   12121            1 :                 },
   12122            1 :             ],
   12123            1 :         );
   12124            1 : 
   12125            1 :         // compact again
   12126            1 :         tline
   12127            1 :             .compact_with_gc(
   12128            1 :                 &cancel,
   12129            1 :                 CompactOptions {
   12130            1 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12131            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12132            1 :                     ..Default::default()
   12133            1 :                 },
   12134            1 :                 &ctx,
   12135            1 :             )
   12136            1 :             .await
   12137            1 :             .unwrap();
   12138            1 :         verify_result().await;
   12139            1 : 
   12140            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12141            1 :         check_layer_map_key_eq(
   12142            1 :             all_layers,
   12143            1 :             vec![
   12144            1 :                 // The original image layer, not compacted
   12145            1 :                 PersistentLayerKey {
   12146            1 :                     key_range: get_key(0)..get_key(10),
   12147            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12148            1 :                     is_delta: false,
   12149            1 :                 },
   12150            1 :                 // The range gets compacted
   12151            1 :                 PersistentLayerKey {
   12152            1 :                     key_range: get_key(1)..get_key(2),
   12153            1 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12154            1 :                     is_delta: true,
   12155            1 :                 },
   12156            1 :                 // Not touched during this iteration of compaction
   12157            1 :                 PersistentLayerKey {
   12158            1 :                     key_range: get_key(8)..get_key(10),
   12159            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12160            1 :                     is_delta: true,
   12161            1 :                 },
   12162            1 :             ],
   12163            1 :         );
   12164            1 : 
   12165            1 :         // final full compaction
   12166            1 :         tline
   12167            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12168            1 :             .await
   12169            1 :             .unwrap();
   12170            1 :         verify_result().await;
   12171            1 : 
   12172            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12173            1 :         check_layer_map_key_eq(
   12174            1 :             all_layers,
   12175            1 :             vec![
   12176            1 :                 // The compacted image layer (full key range)
   12177            1 :                 PersistentLayerKey {
   12178            1 :                     key_range: Key::MIN..Key::MAX,
   12179            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12180            1 :                     is_delta: false,
   12181            1 :                 },
   12182            1 :                 // All other data in the delta layer
   12183            1 :                 PersistentLayerKey {
   12184            1 :                     key_range: get_key(1)..get_key(10),
   12185            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12186            1 :                     is_delta: true,
   12187            1 :                 },
   12188            1 :             ],
   12189            1 :         );
   12190            1 : 
   12191            1 :         Ok(())
   12192            1 :     }
   12193              : 
   12194              :     #[cfg(feature = "testing")]
   12195              :     #[tokio::test]
   12196            1 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12197            1 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12198            1 :         let (tenant, ctx) = harness.load().await;
   12199            1 : 
   12200           13 :         fn get_key(id: u32) -> Key {
   12201           13 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12202           13 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12203           13 :             key.field6 = id;
   12204           13 :             key
   12205           13 :         }
   12206            1 : 
   12207            1 :         let img_layer = (0..10)
   12208           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12209            1 :             .collect_vec();
   12210            1 : 
   12211            1 :         let delta1 = vec![
   12212            1 :             (
   12213            1 :                 get_key(1),
   12214            1 :                 Lsn(0x20),
   12215            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12216            1 :             ),
   12217            1 :             (
   12218            1 :                 get_key(1),
   12219            1 :                 Lsn(0x24),
   12220            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12221            1 :             ),
   12222            1 :             (
   12223            1 :                 get_key(1),
   12224            1 :                 Lsn(0x28),
   12225            1 :                 // This record will fail to redo
   12226            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12227            1 :             ),
   12228            1 :         ];
   12229            1 : 
   12230            1 :         let tline = tenant
   12231            1 :             .create_test_timeline_with_layers(
   12232            1 :                 TIMELINE_ID,
   12233            1 :                 Lsn(0x10),
   12234            1 :                 DEFAULT_PG_VERSION,
   12235            1 :                 &ctx,
   12236            1 :                 vec![], // in-memory layers
   12237            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12238            1 :                     Lsn(0x20)..Lsn(0x30),
   12239            1 :                     delta1,
   12240            1 :                 )], // delta layers
   12241            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12242            1 :                 Lsn(0x50),
   12243            1 :             )
   12244            1 :             .await?;
   12245            1 :         {
   12246            1 :             tline
   12247            1 :                 .applied_gc_cutoff_lsn
   12248            1 :                 .lock_for_write()
   12249            1 :                 .store_and_unlock(Lsn(0x30))
   12250            1 :                 .wait()
   12251            1 :                 .await;
   12252            1 :             // Update GC info
   12253            1 :             let mut guard = tline.gc_info.write().unwrap();
   12254            1 :             *guard = GcInfo {
   12255            1 :                 retain_lsns: vec![],
   12256            1 :                 cutoffs: GcCutoffs {
   12257            1 :                     time: Some(Lsn(0x30)),
   12258            1 :                     space: Lsn(0x30),
   12259            1 :                 },
   12260            1 :                 leases: Default::default(),
   12261            1 :                 within_ancestor_pitr: false,
   12262            1 :             };
   12263            1 :         }
   12264            1 : 
   12265            1 :         let cancel = CancellationToken::new();
   12266            1 : 
   12267            1 :         // Compaction will fail, but should not fire any critical error.
   12268            1 :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12269            1 :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12270            1 :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12271            1 :         let res = tline
   12272            1 :             .compact_with_gc(
   12273            1 :                 &cancel,
   12274            1 :                 CompactOptions {
   12275            1 :                     compact_key_range: None,
   12276            1 :                     compact_lsn_range: None,
   12277            1 :                     ..Default::default()
   12278            1 :                 },
   12279            1 :                 &ctx,
   12280            1 :             )
   12281            1 :             .await;
   12282            1 :         assert!(res.is_err());
   12283            1 : 
   12284            1 :         Ok(())
   12285            1 :     }
   12286              : 
   12287              :     #[cfg(feature = "testing")]
   12288              :     #[tokio::test]
   12289            1 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12290            1 :         use pageserver_api::models::TimelineVisibilityState;
   12291            1 : 
   12292            1 :         use crate::tenant::size::gather_inputs;
   12293            1 : 
   12294            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12295            1 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12296            1 :             pitr_interval: Some(Duration::ZERO),
   12297            1 :             ..Default::default()
   12298            1 :         };
   12299            1 :         let harness = TenantHarness::create_custom(
   12300            1 :             "test_synthetic_size_calculation_with_invisible_branches",
   12301            1 :             tenant_conf,
   12302            1 :             TenantId::generate(),
   12303            1 :             ShardIdentity::unsharded(),
   12304            1 :             Generation::new(0xdeadbeef),
   12305            1 :         )
   12306            1 :         .await?;
   12307            1 :         let (tenant, ctx) = harness.load().await;
   12308            1 :         let main_tline = tenant
   12309            1 :             .create_test_timeline_with_layers(
   12310            1 :                 TIMELINE_ID,
   12311            1 :                 Lsn(0x10),
   12312            1 :                 DEFAULT_PG_VERSION,
   12313            1 :                 &ctx,
   12314            1 :                 vec![],
   12315            1 :                 vec![],
   12316            1 :                 vec![],
   12317            1 :                 Lsn(0x100),
   12318            1 :             )
   12319            1 :             .await?;
   12320            1 : 
   12321            1 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12322            1 :         tenant
   12323            1 :             .branch_timeline_test_with_layers(
   12324            1 :                 &main_tline,
   12325            1 :                 snapshot1,
   12326            1 :                 Some(Lsn(0x20)),
   12327            1 :                 &ctx,
   12328            1 :                 vec![],
   12329            1 :                 vec![],
   12330            1 :                 Lsn(0x50),
   12331            1 :             )
   12332            1 :             .await?;
   12333            1 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12334            1 :         tenant
   12335            1 :             .branch_timeline_test_with_layers(
   12336            1 :                 &main_tline,
   12337            1 :                 snapshot2,
   12338            1 :                 Some(Lsn(0x30)),
   12339            1 :                 &ctx,
   12340            1 :                 vec![],
   12341            1 :                 vec![],
   12342            1 :                 Lsn(0x50),
   12343            1 :             )
   12344            1 :             .await?;
   12345            1 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12346            1 :         tenant
   12347            1 :             .branch_timeline_test_with_layers(
   12348            1 :                 &main_tline,
   12349            1 :                 snapshot3,
   12350            1 :                 Some(Lsn(0x40)),
   12351            1 :                 &ctx,
   12352            1 :                 vec![],
   12353            1 :                 vec![],
   12354            1 :                 Lsn(0x50),
   12355            1 :             )
   12356            1 :             .await?;
   12357            1 :         let limit = Arc::new(Semaphore::new(1));
   12358            1 :         let max_retention_period = None;
   12359            1 :         let mut logical_size_cache = HashMap::new();
   12360            1 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12361            1 :         let cancel = CancellationToken::new();
   12362            1 : 
   12363            1 :         let inputs = gather_inputs(
   12364            1 :             &tenant,
   12365            1 :             &limit,
   12366            1 :             max_retention_period,
   12367            1 :             &mut logical_size_cache,
   12368            1 :             cause,
   12369            1 :             &cancel,
   12370            1 :             &ctx,
   12371            1 :         )
   12372            1 :         .instrument(info_span!(
   12373            1 :             "gather_inputs",
   12374            1 :             tenant_id = "unknown",
   12375            1 :             shard_id = "unknown",
   12376            1 :         ))
   12377            1 :         .await?;
   12378            1 :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12379            1 :         use LsnKind::*;
   12380            1 :         use tenant_size_model::Segment;
   12381            1 :         let ModelInputs { mut segments, .. } = inputs;
   12382           15 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12383            6 :         for segment in segments.iter_mut() {
   12384            6 :             segment.segment.parent = None; // We don't care about the parent for the test
   12385            6 :             segment.segment.size = None; // We don't care about the size for the test
   12386            6 :         }
   12387            1 :         assert_eq!(
   12388            1 :             segments,
   12389            1 :             [
   12390            1 :                 SegmentMeta {
   12391            1 :                     segment: Segment {
   12392            1 :                         parent: None,
   12393            1 :                         lsn: 0x10,
   12394            1 :                         size: None,
   12395            1 :                         needed: false,
   12396            1 :                     },
   12397            1 :                     timeline_id: TIMELINE_ID,
   12398            1 :                     kind: BranchStart,
   12399            1 :                 },
   12400            1 :                 SegmentMeta {
   12401            1 :                     segment: Segment {
   12402            1 :                         parent: None,
   12403            1 :                         lsn: 0x20,
   12404            1 :                         size: None,
   12405            1 :                         needed: false,
   12406            1 :                     },
   12407            1 :                     timeline_id: TIMELINE_ID,
   12408            1 :                     kind: BranchPoint,
   12409            1 :                 },
   12410            1 :                 SegmentMeta {
   12411            1 :                     segment: Segment {
   12412            1 :                         parent: None,
   12413            1 :                         lsn: 0x30,
   12414            1 :                         size: None,
   12415            1 :                         needed: false,
   12416            1 :                     },
   12417            1 :                     timeline_id: TIMELINE_ID,
   12418            1 :                     kind: BranchPoint,
   12419            1 :                 },
   12420            1 :                 SegmentMeta {
   12421            1 :                     segment: Segment {
   12422            1 :                         parent: None,
   12423            1 :                         lsn: 0x40,
   12424            1 :                         size: None,
   12425            1 :                         needed: false,
   12426            1 :                     },
   12427            1 :                     timeline_id: TIMELINE_ID,
   12428            1 :                     kind: BranchPoint,
   12429            1 :                 },
   12430            1 :                 SegmentMeta {
   12431            1 :                     segment: Segment {
   12432            1 :                         parent: None,
   12433            1 :                         lsn: 0x100,
   12434            1 :                         size: None,
   12435            1 :                         needed: false,
   12436            1 :                     },
   12437            1 :                     timeline_id: TIMELINE_ID,
   12438            1 :                     kind: GcCutOff,
   12439            1 :                 }, // we need to retain everything above the last branch point
   12440            1 :                 SegmentMeta {
   12441            1 :                     segment: Segment {
   12442            1 :                         parent: None,
   12443            1 :                         lsn: 0x100,
   12444            1 :                         size: None,
   12445            1 :                         needed: true,
   12446            1 :                     },
   12447            1 :                     timeline_id: TIMELINE_ID,
   12448            1 :                     kind: BranchEnd,
   12449            1 :                 },
   12450            1 :             ]
   12451            1 :         );
   12452            1 : 
   12453            1 :         main_tline
   12454            1 :             .remote_client
   12455            1 :             .schedule_index_upload_for_timeline_invisible_state(
   12456            1 :                 TimelineVisibilityState::Invisible,
   12457            1 :             )?;
   12458            1 :         main_tline.remote_client.wait_completion().await?;
   12459            1 :         let inputs = gather_inputs(
   12460            1 :             &tenant,
   12461            1 :             &limit,
   12462            1 :             max_retention_period,
   12463            1 :             &mut logical_size_cache,
   12464            1 :             cause,
   12465            1 :             &cancel,
   12466            1 :             &ctx,
   12467            1 :         )
   12468            1 :         .instrument(info_span!(
   12469            1 :             "gather_inputs",
   12470            1 :             tenant_id = "unknown",
   12471            1 :             shard_id = "unknown",
   12472            1 :         ))
   12473            1 :         .await?;
   12474            1 :         let ModelInputs { mut segments, .. } = inputs;
   12475           14 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12476            5 :         for segment in segments.iter_mut() {
   12477            5 :             segment.segment.parent = None; // We don't care about the parent for the test
   12478            5 :             segment.segment.size = None; // We don't care about the size for the test
   12479            5 :         }
   12480            1 :         assert_eq!(
   12481            1 :             segments,
   12482            1 :             [
   12483            1 :                 SegmentMeta {
   12484            1 :                     segment: Segment {
   12485            1 :                         parent: None,
   12486            1 :                         lsn: 0x10,
   12487            1 :                         size: None,
   12488            1 :                         needed: false,
   12489            1 :                     },
   12490            1 :                     timeline_id: TIMELINE_ID,
   12491            1 :                     kind: BranchStart,
   12492            1 :                 },
   12493            1 :                 SegmentMeta {
   12494            1 :                     segment: Segment {
   12495            1 :                         parent: None,
   12496            1 :                         lsn: 0x20,
   12497            1 :                         size: None,
   12498            1 :                         needed: false,
   12499            1 :                     },
   12500            1 :                     timeline_id: TIMELINE_ID,
   12501            1 :                     kind: BranchPoint,
   12502            1 :                 },
   12503            1 :                 SegmentMeta {
   12504            1 :                     segment: Segment {
   12505            1 :                         parent: None,
   12506            1 :                         lsn: 0x30,
   12507            1 :                         size: None,
   12508            1 :                         needed: false,
   12509            1 :                     },
   12510            1 :                     timeline_id: TIMELINE_ID,
   12511            1 :                     kind: BranchPoint,
   12512            1 :                 },
   12513            1 :                 SegmentMeta {
   12514            1 :                     segment: Segment {
   12515            1 :                         parent: None,
   12516            1 :                         lsn: 0x40,
   12517            1 :                         size: None,
   12518            1 :                         needed: false,
   12519            1 :                     },
   12520            1 :                     timeline_id: TIMELINE_ID,
   12521            1 :                     kind: BranchPoint,
   12522            1 :                 },
   12523            1 :                 SegmentMeta {
   12524            1 :                     segment: Segment {
   12525            1 :                         parent: None,
   12526            1 :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12527            1 :                         size: None,
   12528            1 :                         needed: true,
   12529            1 :                     },
   12530            1 :                     timeline_id: TIMELINE_ID,
   12531            1 :                     kind: BranchEnd,
   12532            1 :                 },
   12533            1 :             ]
   12534            1 :         );
   12535            1 :         Ok(())
   12536            1 :     }
   12537              : }
        

Generated by: LCOV version 2.1-beta