LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 91bf6c8f32e5e69adde6241313e732fdd6d6e277.info Lines: 76.4 % 8783 6711
Test Date: 2025-03-04 12:19:20 Functions: 59.8 % 453 271

            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              : };
      49              : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
      50              : use storage_broker::BrokerClientChannel;
      51              : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
      52              : use timeline::offload::{OffloadError, offload_timeline};
      53              : use timeline::{
      54              :     CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
      55              : };
      56              : use tokio::io::BufReader;
      57              : use tokio::sync::{Notify, Semaphore, watch};
      58              : use tokio::task::JoinSet;
      59              : use tokio_util::sync::CancellationToken;
      60              : use tracing::*;
      61              : use upload_queue::NotInitialized;
      62              : use utils::circuit_breaker::CircuitBreaker;
      63              : use utils::crashsafe::path_with_suffix_extension;
      64              : use utils::sync::gate::{Gate, GateGuard};
      65              : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
      66              : use utils::try_rcu::ArcSwapExt;
      67              : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
      68              : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
      69              : 
      70              : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf, TenantConf};
      71              : use self::metadata::TimelineMetadata;
      72              : use self::mgr::{GetActiveTenantError, GetTenantError};
      73              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      74              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      75              : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
      76              : use self::timeline::{
      77              :     EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
      78              : };
      79              : use crate::config::PageServerConf;
      80              : use crate::context::{DownloadBehavior, RequestContext};
      81              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
      82              : use crate::l0_flush::L0FlushGlobalState;
      83              : use crate::metrics::{
      84              :     BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
      85              :     INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_STATE_METRIC,
      86              :     TENANT_SYNTHETIC_SIZE_METRIC, remove_tenant_metrics,
      87              : };
      88              : use crate::task_mgr::TaskKind;
      89              : use crate::tenant::config::{LocationMode, TenantConfOpt};
      90              : use crate::tenant::gc_result::GcResult;
      91              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
      92              : use crate::tenant::remote_timeline_client::{
      93              :     INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
      94              : };
      95              : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
      96              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
      97              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
      98              : use crate::virtual_file::VirtualFile;
      99              : use crate::walingest::WalLagCooldown;
     100              : use crate::walredo::PostgresRedoManager;
     101              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
     102              : 
     103            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     104              : use utils::crashsafe;
     105              : use utils::generation::Generation;
     106              : use utils::id::TimelineId;
     107              : use utils::lsn::{Lsn, RecordLsn};
     108              : 
     109              : pub mod blob_io;
     110              : pub mod block_io;
     111              : pub mod vectored_blob_io;
     112              : 
     113              : pub mod disk_btree;
     114              : pub(crate) mod ephemeral_file;
     115              : pub mod layer_map;
     116              : 
     117              : pub mod metadata;
     118              : pub mod remote_timeline_client;
     119              : pub mod storage_layer;
     120              : 
     121              : pub mod checks;
     122              : pub mod config;
     123              : pub mod mgr;
     124              : pub mod secondary;
     125              : pub mod tasks;
     126              : pub mod upload_queue;
     127              : 
     128              : pub(crate) mod timeline;
     129              : 
     130              : pub mod size;
     131              : 
     132              : mod gc_block;
     133              : mod gc_result;
     134              : pub(crate) mod throttle;
     135              : 
     136              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     137              : 
     138              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     139              : // re-export for use in walreceiver
     140              : pub use crate::tenant::timeline::WalReceiverInfo;
     141              : 
     142              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     143              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     144              : 
     145              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     146              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     147              : 
     148              : /// References to shared objects that are passed into each tenant, such
     149              : /// as the shared remote storage client and process initialization state.
     150              : #[derive(Clone)]
     151              : pub struct TenantSharedResources {
     152              :     pub broker_client: storage_broker::BrokerClientChannel,
     153              :     pub remote_storage: GenericRemoteStorage,
     154              :     pub deletion_queue_client: DeletionQueueClient,
     155              :     pub l0_flush_global_state: L0FlushGlobalState,
     156              : }
     157              : 
     158              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     159              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     160              : /// in this struct.
     161              : #[derive(Clone)]
     162              : pub(super) struct AttachedTenantConf {
     163              :     tenant_conf: TenantConfOpt,
     164              :     location: AttachedLocationConfig,
     165              :     /// The deadline before which we are blocked from GC so that
     166              :     /// leases have a chance to be renewed.
     167              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     168              : }
     169              : 
     170              : impl AttachedTenantConf {
     171          452 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     172              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     173              :         //
     174              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     175              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     176              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     177          452 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     178          452 :             Some(
     179          452 :                 tokio::time::Instant::now()
     180          452 :                     + tenant_conf
     181          452 :                         .lsn_lease_length
     182          452 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     183          452 :             )
     184              :         } else {
     185              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     186              :             // because we don't do GC in these modes.
     187            0 :             None
     188              :         };
     189              : 
     190          452 :         Self {
     191          452 :             tenant_conf,
     192          452 :             location,
     193          452 :             lsn_lease_deadline,
     194          452 :         }
     195          452 :     }
     196              : 
     197          452 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     198          452 :         match &location_conf.mode {
     199          452 :             LocationMode::Attached(attach_conf) => {
     200          452 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     201              :             }
     202              :             LocationMode::Secondary(_) => {
     203            0 :                 anyhow::bail!(
     204            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     205            0 :                 )
     206              :             }
     207              :         }
     208          452 :     }
     209              : 
     210         1524 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     211         1524 :         self.lsn_lease_deadline
     212         1524 :             .map(|d| tokio::time::Instant::now() < d)
     213         1524 :             .unwrap_or(false)
     214         1524 :     }
     215              : }
     216              : struct TimelinePreload {
     217              :     timeline_id: TimelineId,
     218              :     client: RemoteTimelineClient,
     219              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     220              :     previous_heatmap: Option<PreviousHeatmap>,
     221              : }
     222              : 
     223              : pub(crate) struct TenantPreload {
     224              :     tenant_manifest: TenantManifest,
     225              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     226              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     227              : }
     228              : 
     229              : /// When we spawn a tenant, there is a special mode for tenant creation that
     230              : /// avoids trying to read anything from remote storage.
     231              : pub(crate) enum SpawnMode {
     232              :     /// Activate as soon as possible
     233              :     Eager,
     234              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     235              :     Lazy,
     236              : }
     237              : 
     238              : ///
     239              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     240              : ///
     241              : pub struct Tenant {
     242              :     // Global pageserver config parameters
     243              :     pub conf: &'static PageServerConf,
     244              : 
     245              :     /// The value creation timestamp, used to measure activation delay, see:
     246              :     /// <https://github.com/neondatabase/neon/issues/4025>
     247              :     constructed_at: Instant,
     248              : 
     249              :     state: watch::Sender<TenantState>,
     250              : 
     251              :     // Overridden tenant-specific config parameters.
     252              :     // We keep TenantConfOpt sturct here to preserve the information
     253              :     // about parameters that are not set.
     254              :     // This is necessary to allow global config updates.
     255              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     256              : 
     257              :     tenant_shard_id: TenantShardId,
     258              : 
     259              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     260              :     shard_identity: ShardIdentity,
     261              : 
     262              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     263              :     /// Does not change over the lifetime of the [`Tenant`] object.
     264              :     ///
     265              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     266              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     267              :     generation: Generation,
     268              : 
     269              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     270              : 
     271              :     /// During timeline creation, we first insert the TimelineId to the
     272              :     /// creating map, then `timelines`, then remove it from the creating map.
     273              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     274              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     275              : 
     276              :     /// Possibly offloaded and archived timelines
     277              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     278              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     279              : 
     280              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     281              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     282              :     /// each other (this could be optimized to coalesce writes if necessary).
     283              :     ///
     284              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     285              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     286              : 
     287              :     // This mutex prevents creation of new timelines during GC.
     288              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     289              :     // `timelines` mutex during all GC iteration
     290              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     291              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     292              :     // timeout...
     293              :     gc_cs: tokio::sync::Mutex<()>,
     294              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     295              : 
     296              :     // provides access to timeline data sitting in the remote storage
     297              :     pub(crate) remote_storage: GenericRemoteStorage,
     298              : 
     299              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     300              :     deletion_queue_client: DeletionQueueClient,
     301              : 
     302              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     303              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     304              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     305              : 
     306              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     307              : 
     308              :     /// Track repeated failures to compact, so that we can back off.
     309              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     310              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     311              : 
     312              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     313              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     314              : 
     315              :     /// Scheduled gc-compaction tasks.
     316              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     317              : 
     318              :     /// If the tenant is in Activating state, notify this to encourage it
     319              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     320              :     /// background warmup.
     321              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     322              : 
     323              :     /// Time it took for the tenant to activate. Zero if not active yet.
     324              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     325              : 
     326              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     327              :     // Timelines' cancellation token.
     328              :     pub(crate) cancel: CancellationToken,
     329              : 
     330              :     // Users of the Tenant such as the page service must take this Gate to avoid
     331              :     // trying to use a Tenant which is shutting down.
     332              :     pub(crate) gate: Gate,
     333              : 
     334              :     /// Throttle applied at the top of [`Timeline::get`].
     335              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     336              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     337              : 
     338              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     339              : 
     340              :     /// An ongoing timeline detach concurrency limiter.
     341              :     ///
     342              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     343              :     /// to have two running at the same time. A different one can be started if an earlier one
     344              :     /// has failed for whatever reason.
     345              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     346              : 
     347              :     /// `index_part.json` based gc blocking reason tracking.
     348              :     ///
     349              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     350              :     /// proceeding.
     351              :     pub(crate) gc_block: gc_block::GcBlock,
     352              : 
     353              :     l0_flush_global_state: L0FlushGlobalState,
     354              : }
     355              : impl std::fmt::Debug for Tenant {
     356            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     357            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     358            0 :     }
     359              : }
     360              : 
     361              : pub(crate) enum WalRedoManager {
     362              :     Prod(WalredoManagerId, PostgresRedoManager),
     363              :     #[cfg(test)]
     364              :     Test(harness::TestRedoManager),
     365              : }
     366              : 
     367              : #[derive(thiserror::Error, Debug)]
     368              : #[error("pageserver is shutting down")]
     369              : pub(crate) struct GlobalShutDown;
     370              : 
     371              : impl WalRedoManager {
     372            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     373            0 :         let id = WalredoManagerId::next();
     374            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     375            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     376            0 :         match &mut *guard {
     377            0 :             Some(map) => {
     378            0 :                 map.insert(id, Arc::downgrade(&arc));
     379            0 :                 Ok(arc)
     380              :             }
     381            0 :             None => Err(GlobalShutDown),
     382              :         }
     383            0 :     }
     384              : }
     385              : 
     386              : impl Drop for WalRedoManager {
     387           20 :     fn drop(&mut self) {
     388           20 :         match self {
     389            0 :             Self::Prod(id, _) => {
     390            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     391            0 :                 if let Some(map) = &mut *guard {
     392            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     393            0 :                 }
     394              :             }
     395              :             #[cfg(test)]
     396           20 :             Self::Test(_) => {
     397           20 :                 // Not applicable to test redo manager
     398           20 :             }
     399              :         }
     400           20 :     }
     401              : }
     402              : 
     403              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     404              : /// the walredo processes outside of the regular order.
     405              : ///
     406              : /// This is necessary to work around a systemd bug where it freezes if there are
     407              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     408              : #[allow(clippy::type_complexity)]
     409              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     410              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     411            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     412              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     413              : pub(crate) struct WalredoManagerId(u64);
     414              : impl WalredoManagerId {
     415            0 :     pub fn next() -> Self {
     416              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     417            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     418            0 :         if id == 0 {
     419            0 :             panic!(
     420            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     421            0 :             );
     422            0 :         }
     423            0 :         Self(id)
     424            0 :     }
     425              : }
     426              : 
     427              : #[cfg(test)]
     428              : impl From<harness::TestRedoManager> for WalRedoManager {
     429          452 :     fn from(mgr: harness::TestRedoManager) -> Self {
     430          452 :         Self::Test(mgr)
     431          452 :     }
     432              : }
     433              : 
     434              : impl WalRedoManager {
     435           12 :     pub(crate) async fn shutdown(&self) -> bool {
     436           12 :         match self {
     437            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     438              :             #[cfg(test)]
     439              :             Self::Test(_) => {
     440              :                 // Not applicable to test redo manager
     441           12 :                 true
     442              :             }
     443              :         }
     444           12 :     }
     445              : 
     446            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     447            0 :         match self {
     448            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     449            0 :             #[cfg(test)]
     450            0 :             Self::Test(_) => {
     451            0 :                 // Not applicable to test redo manager
     452            0 :             }
     453            0 :         }
     454            0 :     }
     455              : 
     456              :     /// # Cancel-Safety
     457              :     ///
     458              :     /// This method is cancellation-safe.
     459         1676 :     pub async fn request_redo(
     460         1676 :         &self,
     461         1676 :         key: pageserver_api::key::Key,
     462         1676 :         lsn: Lsn,
     463         1676 :         base_img: Option<(Lsn, bytes::Bytes)>,
     464         1676 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     465         1676 :         pg_version: u32,
     466         1676 :     ) -> Result<bytes::Bytes, walredo::Error> {
     467         1676 :         match self {
     468            0 :             Self::Prod(_, mgr) => {
     469            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     470            0 :                     .await
     471              :             }
     472              :             #[cfg(test)]
     473         1676 :             Self::Test(mgr) => {
     474         1676 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     475         1676 :                     .await
     476              :             }
     477              :         }
     478         1676 :     }
     479              : 
     480            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     481            0 :         match self {
     482            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     483            0 :             #[cfg(test)]
     484            0 :             WalRedoManager::Test(_) => None,
     485            0 :         }
     486            0 :     }
     487              : }
     488              : 
     489              : /// A very lightweight memory representation of an offloaded timeline.
     490              : ///
     491              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     492              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     493              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     494              : /// more offloaded timelines than we can manage ones that aren't.
     495              : pub struct OffloadedTimeline {
     496              :     pub tenant_shard_id: TenantShardId,
     497              :     pub timeline_id: TimelineId,
     498              :     pub ancestor_timeline_id: Option<TimelineId>,
     499              :     /// Whether to retain the branch lsn at the ancestor or not
     500              :     pub ancestor_retain_lsn: Option<Lsn>,
     501              : 
     502              :     /// When the timeline was archived.
     503              :     ///
     504              :     /// Present for future flattening deliberations.
     505              :     pub archived_at: NaiveDateTime,
     506              : 
     507              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     508              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     509              :     pub delete_progress: TimelineDeleteProgress,
     510              : 
     511              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     512              :     pub deleted_from_ancestor: AtomicBool,
     513              : }
     514              : 
     515              : impl OffloadedTimeline {
     516              :     /// Obtains an offloaded timeline from a given timeline object.
     517              :     ///
     518              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     519              :     /// the timeline is not in a stopped state.
     520              :     /// Panics if the timeline is not archived.
     521            4 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     522            4 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     523            4 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     524            4 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     525            4 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     526            4 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     527            4 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     528            4 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     529              :             } else {
     530            0 :                 (None, None)
     531              :             };
     532            4 :         let archived_at = timeline
     533            4 :             .remote_client
     534            4 :             .archived_at_stopped_queue()?
     535            4 :             .expect("must be called on an archived timeline");
     536            4 :         Ok(Self {
     537            4 :             tenant_shard_id: timeline.tenant_shard_id,
     538            4 :             timeline_id: timeline.timeline_id,
     539            4 :             ancestor_timeline_id,
     540            4 :             ancestor_retain_lsn,
     541            4 :             archived_at,
     542            4 : 
     543            4 :             delete_progress: timeline.delete_progress.clone(),
     544            4 :             deleted_from_ancestor: AtomicBool::new(false),
     545            4 :         })
     546            4 :     }
     547            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     548            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     549            0 :         // by the `initialize_gc_info` function.
     550            0 :         let OffloadedTimelineManifest {
     551            0 :             timeline_id,
     552            0 :             ancestor_timeline_id,
     553            0 :             ancestor_retain_lsn,
     554            0 :             archived_at,
     555            0 :         } = *manifest;
     556            0 :         Self {
     557            0 :             tenant_shard_id,
     558            0 :             timeline_id,
     559            0 :             ancestor_timeline_id,
     560            0 :             ancestor_retain_lsn,
     561            0 :             archived_at,
     562            0 :             delete_progress: TimelineDeleteProgress::default(),
     563            0 :             deleted_from_ancestor: AtomicBool::new(false),
     564            0 :         }
     565            0 :     }
     566            4 :     fn manifest(&self) -> OffloadedTimelineManifest {
     567            4 :         let Self {
     568            4 :             timeline_id,
     569            4 :             ancestor_timeline_id,
     570            4 :             ancestor_retain_lsn,
     571            4 :             archived_at,
     572            4 :             ..
     573            4 :         } = self;
     574            4 :         OffloadedTimelineManifest {
     575            4 :             timeline_id: *timeline_id,
     576            4 :             ancestor_timeline_id: *ancestor_timeline_id,
     577            4 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     578            4 :             archived_at: *archived_at,
     579            4 :         }
     580            4 :     }
     581              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     582            0 :     fn delete_from_ancestor_with_timelines(
     583            0 :         &self,
     584            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     585            0 :     ) {
     586            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     587            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     588              :         {
     589            0 :             if let Some((_, ancestor_timeline)) = timelines
     590            0 :                 .iter()
     591            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     592              :             {
     593            0 :                 let removal_happened = ancestor_timeline
     594            0 :                     .gc_info
     595            0 :                     .write()
     596            0 :                     .unwrap()
     597            0 :                     .remove_child_offloaded(self.timeline_id);
     598            0 :                 if !removal_happened {
     599            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     600            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     601            0 :                 }
     602            0 :             }
     603            0 :         }
     604            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     605            0 :     }
     606              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     607              :     ///
     608              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     609            4 :     fn defuse_for_tenant_drop(&self) {
     610            4 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     611            4 :     }
     612              : }
     613              : 
     614              : impl fmt::Debug for OffloadedTimeline {
     615            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     616            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     617            0 :     }
     618              : }
     619              : 
     620              : impl Drop for OffloadedTimeline {
     621            4 :     fn drop(&mut self) {
     622            4 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     623            0 :             tracing::warn!(
     624            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     625              :                 self.timeline_id
     626              :             );
     627            4 :         }
     628            4 :     }
     629              : }
     630              : 
     631              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     632              : pub enum MaybeOffloaded {
     633              :     Yes,
     634              :     No,
     635              : }
     636              : 
     637              : #[derive(Clone, Debug)]
     638              : pub enum TimelineOrOffloaded {
     639              :     Timeline(Arc<Timeline>),
     640              :     Offloaded(Arc<OffloadedTimeline>),
     641              : }
     642              : 
     643              : impl TimelineOrOffloaded {
     644            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     645            0 :         match self {
     646            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     647            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     648              :             }
     649            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     650            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     651              :             }
     652              :         }
     653            0 :     }
     654            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     655            0 :         self.arc_ref().tenant_shard_id()
     656            0 :     }
     657            0 :     pub fn timeline_id(&self) -> TimelineId {
     658            0 :         self.arc_ref().timeline_id()
     659            0 :     }
     660            4 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     661            4 :         match self {
     662            4 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     663            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     664              :         }
     665            4 :     }
     666            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     667            0 :         match self {
     668            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     669            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     670              :         }
     671            0 :     }
     672              : }
     673              : 
     674              : pub enum TimelineOrOffloadedArcRef<'a> {
     675              :     Timeline(&'a Arc<Timeline>),
     676              :     Offloaded(&'a Arc<OffloadedTimeline>),
     677              : }
     678              : 
     679              : impl TimelineOrOffloadedArcRef<'_> {
     680            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     681            0 :         match self {
     682            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     683            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     684              :         }
     685            0 :     }
     686            0 :     pub fn timeline_id(&self) -> TimelineId {
     687            0 :         match self {
     688            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     689            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     690              :         }
     691            0 :     }
     692              : }
     693              : 
     694              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     695            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     696            0 :         Self::Timeline(timeline)
     697            0 :     }
     698              : }
     699              : 
     700              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     701            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     702            0 :         Self::Offloaded(timeline)
     703            0 :     }
     704              : }
     705              : 
     706              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     707              : pub enum GetTimelineError {
     708              :     #[error("Timeline is shutting down")]
     709              :     ShuttingDown,
     710              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     711              :     NotActive {
     712              :         tenant_id: TenantShardId,
     713              :         timeline_id: TimelineId,
     714              :         state: TimelineState,
     715              :     },
     716              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     717              :     NotFound {
     718              :         tenant_id: TenantShardId,
     719              :         timeline_id: TimelineId,
     720              :     },
     721              : }
     722              : 
     723              : #[derive(Debug, thiserror::Error)]
     724              : pub enum LoadLocalTimelineError {
     725              :     #[error("FailedToLoad")]
     726              :     Load(#[source] anyhow::Error),
     727              :     #[error("FailedToResumeDeletion")]
     728              :     ResumeDeletion(#[source] anyhow::Error),
     729              : }
     730              : 
     731              : #[derive(thiserror::Error)]
     732              : pub enum DeleteTimelineError {
     733              :     #[error("NotFound")]
     734              :     NotFound,
     735              : 
     736              :     #[error("HasChildren")]
     737              :     HasChildren(Vec<TimelineId>),
     738              : 
     739              :     #[error("Timeline deletion is already in progress")]
     740              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     741              : 
     742              :     #[error("Cancelled")]
     743              :     Cancelled,
     744              : 
     745              :     #[error(transparent)]
     746              :     Other(#[from] anyhow::Error),
     747              : }
     748              : 
     749              : impl Debug for DeleteTimelineError {
     750            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     751            0 :         match self {
     752            0 :             Self::NotFound => write!(f, "NotFound"),
     753            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     754            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     755            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     756            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     757              :         }
     758            0 :     }
     759              : }
     760              : 
     761              : #[derive(thiserror::Error)]
     762              : pub enum TimelineArchivalError {
     763              :     #[error("NotFound")]
     764              :     NotFound,
     765              : 
     766              :     #[error("Timeout")]
     767              :     Timeout,
     768              : 
     769              :     #[error("Cancelled")]
     770              :     Cancelled,
     771              : 
     772              :     #[error("ancestor is archived: {}", .0)]
     773              :     HasArchivedParent(TimelineId),
     774              : 
     775              :     #[error("HasUnarchivedChildren")]
     776              :     HasUnarchivedChildren(Vec<TimelineId>),
     777              : 
     778              :     #[error("Timeline archival is already in progress")]
     779              :     AlreadyInProgress,
     780              : 
     781              :     #[error(transparent)]
     782              :     Other(anyhow::Error),
     783              : }
     784              : 
     785              : #[derive(thiserror::Error, Debug)]
     786              : pub(crate) enum TenantManifestError {
     787              :     #[error("Remote storage error: {0}")]
     788              :     RemoteStorage(anyhow::Error),
     789              : 
     790              :     #[error("Cancelled")]
     791              :     Cancelled,
     792              : }
     793              : 
     794              : impl From<TenantManifestError> for TimelineArchivalError {
     795            0 :     fn from(e: TenantManifestError) -> Self {
     796            0 :         match e {
     797            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     798            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     799              :         }
     800            0 :     }
     801              : }
     802              : 
     803              : impl Debug for TimelineArchivalError {
     804            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     805            0 :         match self {
     806            0 :             Self::NotFound => write!(f, "NotFound"),
     807            0 :             Self::Timeout => write!(f, "Timeout"),
     808            0 :             Self::Cancelled => write!(f, "Cancelled"),
     809            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     810            0 :             Self::HasUnarchivedChildren(c) => {
     811            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     812              :             }
     813            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     814            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     815              :         }
     816            0 :     }
     817              : }
     818              : 
     819              : pub enum SetStoppingError {
     820              :     AlreadyStopping(completion::Barrier),
     821              :     Broken,
     822              : }
     823              : 
     824              : impl Debug for SetStoppingError {
     825            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     826            0 :         match self {
     827            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     828            0 :             Self::Broken => write!(f, "Broken"),
     829              :         }
     830            0 :     }
     831              : }
     832              : 
     833              : /// Arguments to [`Tenant::create_timeline`].
     834              : ///
     835              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     836              : /// is `None`, the result of the timeline create call is not deterministic.
     837              : ///
     838              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     839              : #[derive(Debug)]
     840              : pub(crate) enum CreateTimelineParams {
     841              :     Bootstrap(CreateTimelineParamsBootstrap),
     842              :     Branch(CreateTimelineParamsBranch),
     843              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     844              : }
     845              : 
     846              : #[derive(Debug)]
     847              : pub(crate) struct CreateTimelineParamsBootstrap {
     848              :     pub(crate) new_timeline_id: TimelineId,
     849              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     850              :     pub(crate) pg_version: u32,
     851              : }
     852              : 
     853              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     854              : #[derive(Debug)]
     855              : pub(crate) struct CreateTimelineParamsBranch {
     856              :     pub(crate) new_timeline_id: TimelineId,
     857              :     pub(crate) ancestor_timeline_id: TimelineId,
     858              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     859              : }
     860              : 
     861              : #[derive(Debug)]
     862              : pub(crate) struct CreateTimelineParamsImportPgdata {
     863              :     pub(crate) new_timeline_id: TimelineId,
     864              :     pub(crate) location: import_pgdata::index_part_format::Location,
     865              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     866              : }
     867              : 
     868              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     869              : ///
     870              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     871              : ///
     872              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     873              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     874              : ///
     875              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     876              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     877              : ///
     878              : /// Notes:
     879              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     880              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     881              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     882              : ///
     883              : #[derive(Debug, Clone, PartialEq, Eq)]
     884              : pub(crate) enum CreateTimelineIdempotency {
     885              :     /// NB: special treatment, see comment in [`Self`].
     886              :     FailWithConflict,
     887              :     Bootstrap {
     888              :         pg_version: u32,
     889              :     },
     890              :     /// NB: branches always have the same `pg_version` as their ancestor.
     891              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     892              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     893              :     /// determining the child branch pg_version.
     894              :     Branch {
     895              :         ancestor_timeline_id: TimelineId,
     896              :         ancestor_start_lsn: Lsn,
     897              :     },
     898              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     899              : }
     900              : 
     901              : #[derive(Debug, Clone, PartialEq, Eq)]
     902              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     903              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     904              : }
     905              : 
     906              : /// What is returned by [`Tenant::start_creating_timeline`].
     907              : #[must_use]
     908              : enum StartCreatingTimelineResult {
     909              :     CreateGuard(TimelineCreateGuard),
     910              :     Idempotent(Arc<Timeline>),
     911              : }
     912              : 
     913              : enum TimelineInitAndSyncResult {
     914              :     ReadyToActivate(Arc<Timeline>),
     915              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     916              : }
     917              : 
     918              : impl TimelineInitAndSyncResult {
     919            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     920            0 :         match self {
     921            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     922            0 :             _ => None,
     923              :         }
     924            0 :     }
     925              : }
     926              : 
     927              : #[must_use]
     928              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     929              :     timeline: Arc<Timeline>,
     930              :     import_pgdata: import_pgdata::index_part_format::Root,
     931              :     guard: TimelineCreateGuard,
     932              : }
     933              : 
     934              : /// What is returned by [`Tenant::create_timeline`].
     935              : enum CreateTimelineResult {
     936              :     Created(Arc<Timeline>),
     937              :     Idempotent(Arc<Timeline>),
     938              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     939              :     /// we return this result, nor will this concrete object ever be added there.
     940              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     941              :     ImportSpawned(Arc<Timeline>),
     942              : }
     943              : 
     944              : impl CreateTimelineResult {
     945            0 :     fn discriminant(&self) -> &'static str {
     946            0 :         match self {
     947            0 :             Self::Created(_) => "Created",
     948            0 :             Self::Idempotent(_) => "Idempotent",
     949            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     950              :         }
     951            0 :     }
     952            0 :     fn timeline(&self) -> &Arc<Timeline> {
     953            0 :         match self {
     954            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     955            0 :         }
     956            0 :     }
     957              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     958              :     #[cfg(test)]
     959          460 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     960          460 :         match self {
     961          460 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     962          460 :         }
     963          460 :     }
     964              : }
     965              : 
     966              : #[derive(thiserror::Error, Debug)]
     967              : pub enum CreateTimelineError {
     968              :     #[error("creation of timeline with the given ID is in progress")]
     969              :     AlreadyCreating,
     970              :     #[error("timeline already exists with different parameters")]
     971              :     Conflict,
     972              :     #[error(transparent)]
     973              :     AncestorLsn(anyhow::Error),
     974              :     #[error("ancestor timeline is not active")]
     975              :     AncestorNotActive,
     976              :     #[error("ancestor timeline is archived")]
     977              :     AncestorArchived,
     978              :     #[error("tenant shutting down")]
     979              :     ShuttingDown,
     980              :     #[error(transparent)]
     981              :     Other(#[from] anyhow::Error),
     982              : }
     983              : 
     984              : #[derive(thiserror::Error, Debug)]
     985              : pub enum InitdbError {
     986              :     #[error("Operation was cancelled")]
     987              :     Cancelled,
     988              :     #[error(transparent)]
     989              :     Other(anyhow::Error),
     990              :     #[error(transparent)]
     991              :     Inner(postgres_initdb::Error),
     992              : }
     993              : 
     994              : enum CreateTimelineCause {
     995              :     Load,
     996              :     Delete,
     997              : }
     998              : 
     999              : enum LoadTimelineCause {
    1000              :     Attach,
    1001              :     Unoffload,
    1002              :     ImportPgdata {
    1003              :         create_guard: TimelineCreateGuard,
    1004              :         activate: ActivateTimelineArgs,
    1005              :     },
    1006              : }
    1007              : 
    1008              : #[derive(thiserror::Error, Debug)]
    1009              : pub(crate) enum GcError {
    1010              :     // The tenant is shutting down
    1011              :     #[error("tenant shutting down")]
    1012              :     TenantCancelled,
    1013              : 
    1014              :     // The tenant is shutting down
    1015              :     #[error("timeline shutting down")]
    1016              :     TimelineCancelled,
    1017              : 
    1018              :     // The tenant is in a state inelegible to run GC
    1019              :     #[error("not active")]
    1020              :     NotActive,
    1021              : 
    1022              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1023              :     #[error("not active")]
    1024              :     BadLsn { why: String },
    1025              : 
    1026              :     // A remote storage error while scheduling updates after compaction
    1027              :     #[error(transparent)]
    1028              :     Remote(anyhow::Error),
    1029              : 
    1030              :     // An error reading while calculating GC cutoffs
    1031              :     #[error(transparent)]
    1032              :     GcCutoffs(PageReconstructError),
    1033              : 
    1034              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1035              :     #[error("timeline not found")]
    1036              :     TimelineNotFound,
    1037              : }
    1038              : 
    1039              : impl From<PageReconstructError> for GcError {
    1040            0 :     fn from(value: PageReconstructError) -> Self {
    1041            0 :         match value {
    1042            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1043            0 :             other => Self::GcCutoffs(other),
    1044              :         }
    1045            0 :     }
    1046              : }
    1047              : 
    1048              : impl From<NotInitialized> for GcError {
    1049            0 :     fn from(value: NotInitialized) -> Self {
    1050            0 :         match value {
    1051            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1052            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1053              :         }
    1054            0 :     }
    1055              : }
    1056              : 
    1057              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1058            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1059            0 :         GcError::TimelineCancelled
    1060            0 :     }
    1061              : }
    1062              : 
    1063              : #[derive(thiserror::Error, Debug)]
    1064              : pub(crate) enum LoadConfigError {
    1065              :     #[error("TOML deserialization error: '{0}'")]
    1066              :     DeserializeToml(#[from] toml_edit::de::Error),
    1067              : 
    1068              :     #[error("Config not found at {0}")]
    1069              :     NotFound(Utf8PathBuf),
    1070              : }
    1071              : 
    1072              : impl Tenant {
    1073              :     /// Yet another helper for timeline initialization.
    1074              :     ///
    1075              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1076              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1077              :     /// - Downloads remote index file and adds remote files to the layer map
    1078              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1079              :     ///
    1080              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1081              :     /// it is marked as Active.
    1082              :     #[allow(clippy::too_many_arguments)]
    1083           12 :     async fn timeline_init_and_sync(
    1084           12 :         self: &Arc<Self>,
    1085           12 :         timeline_id: TimelineId,
    1086           12 :         resources: TimelineResources,
    1087           12 :         mut index_part: IndexPart,
    1088           12 :         metadata: TimelineMetadata,
    1089           12 :         previous_heatmap: Option<PreviousHeatmap>,
    1090           12 :         ancestor: Option<Arc<Timeline>>,
    1091           12 :         cause: LoadTimelineCause,
    1092           12 :         ctx: &RequestContext,
    1093           12 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1094           12 :         let tenant_id = self.tenant_shard_id;
    1095           12 : 
    1096           12 :         let import_pgdata = index_part.import_pgdata.take();
    1097           12 :         let idempotency = match &import_pgdata {
    1098            0 :             Some(import_pgdata) => {
    1099            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1100            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1101            0 :                 })
    1102              :             }
    1103              :             None => {
    1104           12 :                 if metadata.ancestor_timeline().is_none() {
    1105            8 :                     CreateTimelineIdempotency::Bootstrap {
    1106            8 :                         pg_version: metadata.pg_version(),
    1107            8 :                     }
    1108              :                 } else {
    1109            4 :                     CreateTimelineIdempotency::Branch {
    1110            4 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1111            4 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1112            4 :                     }
    1113              :                 }
    1114              :             }
    1115              :         };
    1116              : 
    1117           12 :         let timeline = self.create_timeline_struct(
    1118           12 :             timeline_id,
    1119           12 :             &metadata,
    1120           12 :             previous_heatmap,
    1121           12 :             ancestor.clone(),
    1122           12 :             resources,
    1123           12 :             CreateTimelineCause::Load,
    1124           12 :             idempotency.clone(),
    1125           12 :             index_part.gc_compaction.clone(),
    1126           12 :             index_part.rel_size_migration.clone(),
    1127           12 :         )?;
    1128           12 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1129           12 :         anyhow::ensure!(
    1130           12 :             disk_consistent_lsn.is_valid(),
    1131            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1132              :         );
    1133           12 :         assert_eq!(
    1134           12 :             disk_consistent_lsn,
    1135           12 :             metadata.disk_consistent_lsn(),
    1136            0 :             "these are used interchangeably"
    1137              :         );
    1138              : 
    1139           12 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1140              : 
    1141           12 :         timeline
    1142           12 :             .load_layer_map(disk_consistent_lsn, index_part)
    1143           12 :             .await
    1144           12 :             .with_context(|| {
    1145            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1146           12 :             })?;
    1147              : 
    1148              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1149              :         // to the archival operation. To allow warming this timeline up, generate
    1150              :         // a previous heatmap which contains all visible layers in the layer map.
    1151              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1152              :         // for the timeline.
    1153           12 :         if matches!(cause, LoadTimelineCause::Unoffload) {
    1154            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1155            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1156            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1157              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1158              :                 // If the current branch point greater than the previous one use the the heatmap
    1159              :                 // we just generated - it should include more layers.
    1160            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1161            0 :                     tline
    1162            0 :                         .previous_heatmap
    1163            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1164            0 :                 } else {
    1165            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1166              :                 }
    1167              : 
    1168            0 :                 match tline.ancestor_timeline() {
    1169            0 :                     Some(ancestor) => {
    1170            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1171              :                             // Ancestor timeline is shutting down.
    1172            0 :                             break;
    1173            0 :                         }
    1174            0 : 
    1175            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1176              :                     }
    1177            0 :                     None => {
    1178            0 :                         tline_ending_at = None;
    1179            0 :                     }
    1180              :                 }
    1181              :             }
    1182           12 :         }
    1183              : 
    1184            0 :         match import_pgdata {
    1185            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1186            0 :                 match cause {
    1187            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1188              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1189            0 :                         unreachable!(
    1190            0 :                             "ImportPgdata should not be reloading timeline import is done and persisted as such in s3"
    1191            0 :                         )
    1192              :                     }
    1193              :                 }
    1194            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1195            0 :                 if !guard.insert(timeline_id) {
    1196              :                     // We should never try and load the same timeline twice during startup
    1197            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1198            0 :                 }
    1199            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1200            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1201            0 :                     owning_tenant: self.clone(),
    1202            0 :                     timeline_id,
    1203            0 :                     idempotency,
    1204            0 :                     // The users of this specific return value don't need the timline_path in there.
    1205            0 :                     timeline_path: timeline
    1206            0 :                         .conf
    1207            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1208            0 :                 };
    1209            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1210            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1211            0 :                         timeline,
    1212            0 :                         import_pgdata,
    1213            0 :                         guard: timeline_create_guard,
    1214            0 :                     },
    1215            0 :                 ))
    1216              :             }
    1217              :             Some(_) | None => {
    1218              :                 {
    1219           12 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1220           12 :                     match timelines_accessor.entry(timeline_id) {
    1221              :                         // We should never try and load the same timeline twice during startup
    1222              :                         Entry::Occupied(_) => {
    1223            0 :                             unreachable!(
    1224            0 :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1225            0 :                             );
    1226              :                         }
    1227           12 :                         Entry::Vacant(v) => {
    1228           12 :                             v.insert(Arc::clone(&timeline));
    1229           12 :                             timeline.maybe_spawn_flush_loop();
    1230           12 :                         }
    1231              :                     }
    1232              :                 }
    1233              : 
    1234              :                 // Sanity check: a timeline should have some content.
    1235           12 :                 anyhow::ensure!(
    1236           12 :                     ancestor.is_some()
    1237            8 :                         || timeline
    1238            8 :                             .layers
    1239            8 :                             .read()
    1240            8 :                             .await
    1241            8 :                             .layer_map()
    1242            8 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1243            8 :                             .iter_historic_layers()
    1244            8 :                             .next()
    1245            8 :                             .is_some(),
    1246            0 :                     "Timeline has no ancestor and no layer files"
    1247              :                 );
    1248              : 
    1249           12 :                 match cause {
    1250           12 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1251              :                     LoadTimelineCause::ImportPgdata {
    1252            0 :                         create_guard,
    1253            0 :                         activate,
    1254            0 :                     } => {
    1255            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1256            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1257            0 :                         match activate {
    1258            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1259            0 :                                 info!("activating timeline after reload from pgdata import task");
    1260            0 :                                 timeline.activate(self.clone(), broker_client, None, ctx);
    1261              :                             }
    1262            0 :                             ActivateTimelineArgs::No => (),
    1263              :                         }
    1264            0 :                         drop(create_guard);
    1265              :                     }
    1266              :                 }
    1267              : 
    1268           12 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1269              :             }
    1270              :         }
    1271           12 :     }
    1272              : 
    1273              :     /// Attach a tenant that's available in cloud storage.
    1274              :     ///
    1275              :     /// This returns quickly, after just creating the in-memory object
    1276              :     /// Tenant struct and launching a background task to download
    1277              :     /// the remote index files.  On return, the tenant is most likely still in
    1278              :     /// Attaching state, and it will become Active once the background task
    1279              :     /// finishes. You can use wait_until_active() to wait for the task to
    1280              :     /// complete.
    1281              :     ///
    1282              :     #[allow(clippy::too_many_arguments)]
    1283            0 :     pub(crate) fn spawn(
    1284            0 :         conf: &'static PageServerConf,
    1285            0 :         tenant_shard_id: TenantShardId,
    1286            0 :         resources: TenantSharedResources,
    1287            0 :         attached_conf: AttachedTenantConf,
    1288            0 :         shard_identity: ShardIdentity,
    1289            0 :         init_order: Option<InitializationOrder>,
    1290            0 :         mode: SpawnMode,
    1291            0 :         ctx: &RequestContext,
    1292            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1293            0 :         let wal_redo_manager =
    1294            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1295              : 
    1296              :         let TenantSharedResources {
    1297            0 :             broker_client,
    1298            0 :             remote_storage,
    1299            0 :             deletion_queue_client,
    1300            0 :             l0_flush_global_state,
    1301            0 :         } = resources;
    1302            0 : 
    1303            0 :         let attach_mode = attached_conf.location.attach_mode;
    1304            0 :         let generation = attached_conf.location.generation;
    1305            0 : 
    1306            0 :         let tenant = Arc::new(Tenant::new(
    1307            0 :             TenantState::Attaching,
    1308            0 :             conf,
    1309            0 :             attached_conf,
    1310            0 :             shard_identity,
    1311            0 :             Some(wal_redo_manager),
    1312            0 :             tenant_shard_id,
    1313            0 :             remote_storage.clone(),
    1314            0 :             deletion_queue_client,
    1315            0 :             l0_flush_global_state,
    1316            0 :         ));
    1317            0 : 
    1318            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1319            0 :         // we shut down while attaching.
    1320            0 :         let attach_gate_guard = tenant
    1321            0 :             .gate
    1322            0 :             .enter()
    1323            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1324            0 : 
    1325            0 :         // Do all the hard work in the background
    1326            0 :         let tenant_clone = Arc::clone(&tenant);
    1327            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1328            0 :         task_mgr::spawn(
    1329            0 :             &tokio::runtime::Handle::current(),
    1330            0 :             TaskKind::Attach,
    1331            0 :             tenant_shard_id,
    1332            0 :             None,
    1333            0 :             "attach tenant",
    1334            0 :             async move {
    1335            0 : 
    1336            0 :                 info!(
    1337              :                     ?attach_mode,
    1338            0 :                     "Attaching tenant"
    1339              :                 );
    1340              : 
    1341            0 :                 let _gate_guard = attach_gate_guard;
    1342            0 : 
    1343            0 :                 // Is this tenant being spawned as part of process startup?
    1344            0 :                 let starting_up = init_order.is_some();
    1345            0 :                 scopeguard::defer! {
    1346            0 :                     if starting_up {
    1347            0 :                         TENANT.startup_complete.inc();
    1348            0 :                     }
    1349            0 :                 }
    1350              : 
    1351              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1352              :                 enum BrokenVerbosity {
    1353              :                     Error,
    1354              :                     Info
    1355              :                 }
    1356            0 :                 let make_broken =
    1357            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1358            0 :                         match verbosity {
    1359              :                             BrokenVerbosity::Info => {
    1360            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1361              :                             },
    1362              :                             BrokenVerbosity::Error => {
    1363            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1364              :                             }
    1365              :                         }
    1366            0 :                         t.state.send_modify(|state| {
    1367            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1368            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1369            0 :                             assert!(
    1370            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1371            0 :                                 "the attach task owns the tenant state until activation is complete"
    1372              :                             );
    1373              : 
    1374            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    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(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    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              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1433              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1434              :                             // just shutting down), but ensures progress.
    1435            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1436            0 :                             return Ok(());
    1437              :                         },
    1438              :                     )
    1439              :                 } else {
    1440              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1441              :                     // concurrent_tenant_warmup queue
    1442            0 :                     AttachType::Normal
    1443              :                 };
    1444              : 
    1445            0 :                 let preload = match &mode {
    1446              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1447            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1448            0 :                         let res = tenant_clone
    1449            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1450            0 :                             .await;
    1451            0 :                         match res {
    1452            0 :                             Ok(p) => Some(p),
    1453            0 :                             Err(e) => {
    1454            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1455            0 :                                 return Ok(());
    1456              :                             }
    1457              :                         }
    1458              :                     }
    1459              : 
    1460              :                 };
    1461              : 
    1462              :                 // Remote preload is complete.
    1463            0 :                 drop(remote_load_completion);
    1464            0 : 
    1465            0 : 
    1466            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1467            0 :                 let attach_start = std::time::Instant::now();
    1468            0 :                 let attached = {
    1469            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1470            0 :                     tenant_clone.attach(preload, &ctx).await
    1471              :                 };
    1472            0 :                 let attach_duration = attach_start.elapsed();
    1473            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1474            0 : 
    1475            0 :                 match attached {
    1476              :                     Ok(()) => {
    1477            0 :                         info!("attach finished, activating");
    1478            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1479              :                     }
    1480            0 :                     Err(e) => {
    1481            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1482            0 :                     }
    1483              :                 }
    1484              : 
    1485              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1486              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1487              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1488              :                 //
    1489              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1490              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1491              :                 // then warmup will wait for that before proceeding to the next tenant.
    1492            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1493            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1494            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1495            0 :                     while futs.next().await.is_some() {}
    1496            0 :                     tracing::info!("Warm-up complete");
    1497            0 :                 }
    1498              : 
    1499            0 :                 Ok(())
    1500            0 :             }
    1501            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1502              :         );
    1503            0 :         Ok(tenant)
    1504            0 :     }
    1505              : 
    1506              :     #[instrument(skip_all)]
    1507              :     pub(crate) async fn preload(
    1508              :         self: &Arc<Self>,
    1509              :         remote_storage: &GenericRemoteStorage,
    1510              :         cancel: CancellationToken,
    1511              :     ) -> anyhow::Result<TenantPreload> {
    1512              :         span::debug_assert_current_span_has_tenant_id();
    1513              :         // Get list of remote timelines
    1514              :         // download index files for every tenant timeline
    1515              :         info!("listing remote timelines");
    1516              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1517              :             remote_storage,
    1518              :             self.tenant_shard_id,
    1519              :             cancel.clone(),
    1520              :         )
    1521              :         .await?;
    1522              :         let (offloaded_add, tenant_manifest) =
    1523              :             match remote_timeline_client::download_tenant_manifest(
    1524              :                 remote_storage,
    1525              :                 &self.tenant_shard_id,
    1526              :                 self.generation,
    1527              :                 &cancel,
    1528              :             )
    1529              :             .await
    1530              :             {
    1531              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1532              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1533              :                     tenant_manifest,
    1534              :                 ),
    1535              :                 Err(DownloadError::NotFound) => {
    1536              :                     ("no manifest".to_string(), TenantManifest::empty())
    1537              :                 }
    1538              :                 Err(e) => Err(e)?,
    1539              :             };
    1540              : 
    1541              :         info!(
    1542              :             "found {} timelines, and {offloaded_add}",
    1543              :             remote_timeline_ids.len()
    1544              :         );
    1545              : 
    1546              :         for k in other_keys {
    1547              :             warn!("Unexpected non timeline key {k}");
    1548              :         }
    1549              : 
    1550              :         // Avoid downloading IndexPart of offloaded timelines.
    1551              :         let mut offloaded_with_prefix = HashSet::new();
    1552              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1553              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1554              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1555              :             } else {
    1556              :                 // We'll take care later of timelines in the manifest without a prefix
    1557              :             }
    1558              :         }
    1559              : 
    1560              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1561              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1562              :         // will kick the secondary in any case and cause a download.
    1563              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1564              : 
    1565              :         let timelines = self
    1566              :             .load_timelines_metadata(
    1567              :                 remote_timeline_ids,
    1568              :                 remote_storage,
    1569              :                 maybe_heatmap_at,
    1570              :                 cancel,
    1571              :             )
    1572              :             .await?;
    1573              : 
    1574              :         Ok(TenantPreload {
    1575              :             tenant_manifest,
    1576              :             timelines: timelines
    1577              :                 .into_iter()
    1578           12 :                 .map(|(id, tl)| (id, Some(tl)))
    1579            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1580              :                 .collect(),
    1581              :         })
    1582              :     }
    1583              : 
    1584          452 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1585          452 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1586          452 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1587            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1588            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1589            0 :                 Err(err) => {
    1590            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1591            0 :                     None
    1592              :                 }
    1593              :             },
    1594          452 :             Err(err) => match err.kind() {
    1595          452 :                 std::io::ErrorKind::NotFound => None,
    1596              :                 _ => {
    1597            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1598            0 :                     None
    1599              :                 }
    1600              :             },
    1601              :         }
    1602          452 :     }
    1603              : 
    1604              :     ///
    1605              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1606              :     ///
    1607              :     /// No background tasks are started as part of this routine.
    1608              :     ///
    1609          452 :     async fn attach(
    1610          452 :         self: &Arc<Tenant>,
    1611          452 :         preload: Option<TenantPreload>,
    1612          452 :         ctx: &RequestContext,
    1613          452 :     ) -> anyhow::Result<()> {
    1614          452 :         span::debug_assert_current_span_has_tenant_id();
    1615          452 : 
    1616          452 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1617              : 
    1618          452 :         let Some(preload) = preload else {
    1619            0 :             anyhow::bail!(
    1620            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1621            0 :             );
    1622              :         };
    1623              : 
    1624          452 :         let mut offloaded_timeline_ids = HashSet::new();
    1625          452 :         let mut offloaded_timelines_list = Vec::new();
    1626          452 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1627            0 :             let timeline_id = timeline_manifest.timeline_id;
    1628            0 :             let offloaded_timeline =
    1629            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1630            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1631            0 :             offloaded_timeline_ids.insert(timeline_id);
    1632            0 :         }
    1633              :         // Complete deletions for offloaded timeline id's from manifest.
    1634              :         // The manifest will be uploaded later in this function.
    1635          452 :         offloaded_timelines_list
    1636          452 :             .retain(|(offloaded_id, offloaded)| {
    1637            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1638            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1639            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1640            0 :                 if delete {
    1641            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1642            0 :                     offloaded.defuse_for_tenant_drop();
    1643            0 :                 }
    1644            0 :                 !delete
    1645          452 :         });
    1646          452 : 
    1647          452 :         let mut timelines_to_resume_deletions = vec![];
    1648          452 : 
    1649          452 :         let mut remote_index_and_client = HashMap::new();
    1650          452 :         let mut timeline_ancestors = HashMap::new();
    1651          452 :         let mut existent_timelines = HashSet::new();
    1652          464 :         for (timeline_id, preload) in preload.timelines {
    1653           12 :             let Some(preload) = preload else { continue };
    1654              :             // This is an invariant of the `preload` function's API
    1655           12 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1656           12 :             let index_part = match preload.index_part {
    1657           12 :                 Ok(i) => {
    1658           12 :                     debug!("remote index part exists for timeline {timeline_id}");
    1659              :                     // We found index_part on the remote, this is the standard case.
    1660           12 :                     existent_timelines.insert(timeline_id);
    1661           12 :                     i
    1662              :                 }
    1663              :                 Err(DownloadError::NotFound) => {
    1664              :                     // There is no index_part on the remote. We only get here
    1665              :                     // if there is some prefix for the timeline in the remote storage.
    1666              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1667              :                     // remnant from a prior incomplete creation or deletion attempt.
    1668              :                     // Delete the local directory as the deciding criterion for a
    1669              :                     // timeline's existence is presence of index_part.
    1670            0 :                     info!(%timeline_id, "index_part not found on remote");
    1671            0 :                     continue;
    1672              :                 }
    1673            0 :                 Err(DownloadError::Fatal(why)) => {
    1674            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1675            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1676            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1677            0 :                     anyhow::bail!(why.to_string());
    1678              :                 }
    1679            0 :                 Err(e) => {
    1680            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1681            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1682            0 :                     // as it might be a temporary issue and we don't want to re-download
    1683            0 :                     // everything after it resolves.
    1684            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1685              : 
    1686            0 :                     existent_timelines.insert(timeline_id);
    1687            0 :                     continue;
    1688              :                 }
    1689              :             };
    1690           12 :             match index_part {
    1691           12 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1692           12 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1693           12 :                     remote_index_and_client.insert(
    1694           12 :                         timeline_id,
    1695           12 :                         (index_part, preload.client, preload.previous_heatmap),
    1696           12 :                     );
    1697           12 :                 }
    1698            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1699            0 :                     info!(
    1700            0 :                         "timeline {} is deleted, picking to resume deletion",
    1701              :                         timeline_id
    1702              :                     );
    1703            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1704              :                 }
    1705              :             }
    1706              :         }
    1707              : 
    1708          452 :         let mut gc_blocks = HashMap::new();
    1709              : 
    1710              :         // For every timeline, download the metadata file, scan the local directory,
    1711              :         // and build a layer map that contains an entry for each remote and local
    1712              :         // layer file.
    1713          452 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1714          464 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1715           12 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1716           12 :                 .remove(&timeline_id)
    1717           12 :                 .expect("just put it in above");
    1718              : 
    1719           12 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1720              :                 // could just filter these away, but it helps while testing
    1721            0 :                 anyhow::ensure!(
    1722            0 :                     !blocking.reasons.is_empty(),
    1723            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1724              :                 );
    1725            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1726            0 :                 assert!(prev.is_none());
    1727           12 :             }
    1728              : 
    1729              :             // TODO again handle early failure
    1730           12 :             let effect = self
    1731           12 :                 .load_remote_timeline(
    1732           12 :                     timeline_id,
    1733           12 :                     index_part,
    1734           12 :                     remote_metadata,
    1735           12 :                     previous_heatmap,
    1736           12 :                     self.get_timeline_resources_for(remote_client),
    1737           12 :                     LoadTimelineCause::Attach,
    1738           12 :                     ctx,
    1739           12 :                 )
    1740           12 :                 .await
    1741           12 :                 .with_context(|| {
    1742            0 :                     format!(
    1743            0 :                         "failed to load remote timeline {} for tenant {}",
    1744            0 :                         timeline_id, self.tenant_shard_id
    1745            0 :                     )
    1746           12 :                 })?;
    1747              : 
    1748           12 :             match effect {
    1749           12 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1750           12 :                     // activation happens later, on Tenant::activate
    1751           12 :                 }
    1752              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1753              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1754            0 :                         timeline,
    1755            0 :                         import_pgdata,
    1756            0 :                         guard,
    1757            0 :                     },
    1758            0 :                 ) => {
    1759            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1760            0 :                         timeline,
    1761            0 :                         import_pgdata,
    1762            0 :                         ActivateTimelineArgs::No,
    1763            0 :                         guard,
    1764            0 :                     ));
    1765            0 :                 }
    1766              :             }
    1767              :         }
    1768              : 
    1769              :         // Walk through deleted timelines, resume deletion
    1770          452 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1771            0 :             remote_timeline_client
    1772            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1773            0 :                 .context("init queue stopped")
    1774            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1775              : 
    1776            0 :             DeleteTimelineFlow::resume_deletion(
    1777            0 :                 Arc::clone(self),
    1778            0 :                 timeline_id,
    1779            0 :                 &index_part.metadata,
    1780            0 :                 remote_timeline_client,
    1781            0 :             )
    1782            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1783            0 :             .await
    1784            0 :             .context("resume_deletion")
    1785            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1786              :         }
    1787          452 :         let needs_manifest_upload =
    1788          452 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1789          452 :         {
    1790          452 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1791          452 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1792          452 :         }
    1793          452 :         if needs_manifest_upload {
    1794            0 :             self.store_tenant_manifest().await?;
    1795          452 :         }
    1796              : 
    1797              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1798              :         // IndexPart is the source of truth.
    1799          452 :         self.clean_up_timelines(&existent_timelines)?;
    1800              : 
    1801          452 :         self.gc_block.set_scanned(gc_blocks);
    1802          452 : 
    1803          452 :         fail::fail_point!("attach-before-activate", |_| {
    1804            0 :             anyhow::bail!("attach-before-activate");
    1805          452 :         });
    1806          452 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1807              : 
    1808          452 :         info!("Done");
    1809              : 
    1810          452 :         Ok(())
    1811          452 :     }
    1812              : 
    1813              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1814              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1815              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1816          452 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1817          452 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1818              : 
    1819          452 :         let entries = match timelines_dir.read_dir_utf8() {
    1820          452 :             Ok(d) => d,
    1821            0 :             Err(e) => {
    1822            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1823            0 :                     return Ok(());
    1824              :                 } else {
    1825            0 :                     return Err(e).context("list timelines directory for tenant");
    1826              :                 }
    1827              :             }
    1828              :         };
    1829              : 
    1830          468 :         for entry in entries {
    1831           16 :             let entry = entry.context("read timeline dir entry")?;
    1832           16 :             let entry_path = entry.path();
    1833              : 
    1834           16 :             let purge = if crate::is_temporary(entry_path) {
    1835            0 :                 true
    1836              :             } else {
    1837           16 :                 match TimelineId::try_from(entry_path.file_name()) {
    1838           16 :                     Ok(i) => {
    1839           16 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1840           16 :                         !existent_timelines.contains(&i)
    1841              :                     }
    1842            0 :                     Err(e) => {
    1843            0 :                         tracing::warn!(
    1844            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1845              :                         );
    1846              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1847            0 :                         false
    1848              :                     }
    1849              :                 }
    1850              :             };
    1851              : 
    1852           16 :             if purge {
    1853            4 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1854            4 :                 if let Err(e) = match entry.file_type() {
    1855            4 :                     Ok(t) => if t.is_dir() {
    1856            4 :                         std::fs::remove_dir_all(entry_path)
    1857              :                     } else {
    1858            0 :                         std::fs::remove_file(entry_path)
    1859              :                     }
    1860            4 :                     .or_else(fs_ext::ignore_not_found),
    1861            0 :                     Err(e) => Err(e),
    1862              :                 } {
    1863            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1864            4 :                 }
    1865           12 :             }
    1866              :         }
    1867              : 
    1868          452 :         Ok(())
    1869          452 :     }
    1870              : 
    1871              :     /// Get sum of all remote timelines sizes
    1872              :     ///
    1873              :     /// This function relies on the index_part instead of listing the remote storage
    1874            0 :     pub fn remote_size(&self) -> u64 {
    1875            0 :         let mut size = 0;
    1876              : 
    1877            0 :         for timeline in self.list_timelines() {
    1878            0 :             size += timeline.remote_client.get_remote_physical_size();
    1879            0 :         }
    1880              : 
    1881            0 :         size
    1882            0 :     }
    1883              : 
    1884              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1885              :     #[allow(clippy::too_many_arguments)]
    1886              :     async fn load_remote_timeline(
    1887              :         self: &Arc<Self>,
    1888              :         timeline_id: TimelineId,
    1889              :         index_part: IndexPart,
    1890              :         remote_metadata: TimelineMetadata,
    1891              :         previous_heatmap: Option<PreviousHeatmap>,
    1892              :         resources: TimelineResources,
    1893              :         cause: LoadTimelineCause,
    1894              :         ctx: &RequestContext,
    1895              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1896              :         span::debug_assert_current_span_has_tenant_id();
    1897              : 
    1898              :         info!("downloading index file for timeline {}", timeline_id);
    1899              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1900              :             .await
    1901              :             .context("Failed to create new timeline directory")?;
    1902              : 
    1903              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1904              :             let timelines = self.timelines.lock().unwrap();
    1905              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1906            0 :                 || {
    1907            0 :                     anyhow::anyhow!(
    1908            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1909            0 :                     )
    1910            0 :                 },
    1911              :             )?))
    1912              :         } else {
    1913              :             None
    1914              :         };
    1915              : 
    1916              :         self.timeline_init_and_sync(
    1917              :             timeline_id,
    1918              :             resources,
    1919              :             index_part,
    1920              :             remote_metadata,
    1921              :             previous_heatmap,
    1922              :             ancestor,
    1923              :             cause,
    1924              :             ctx,
    1925              :         )
    1926              :         .await
    1927              :     }
    1928              : 
    1929          452 :     async fn load_timelines_metadata(
    1930          452 :         self: &Arc<Tenant>,
    1931          452 :         timeline_ids: HashSet<TimelineId>,
    1932          452 :         remote_storage: &GenericRemoteStorage,
    1933          452 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    1934          452 :         cancel: CancellationToken,
    1935          452 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1936          452 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    1937          452 : 
    1938          452 :         let mut part_downloads = JoinSet::new();
    1939          464 :         for timeline_id in timeline_ids {
    1940           12 :             let cancel_clone = cancel.clone();
    1941           12 : 
    1942           12 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    1943            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    1944            0 :                     heatmap: h,
    1945            0 :                     read_at: hs.1,
    1946            0 :                     end_lsn: None,
    1947            0 :                 })
    1948           12 :             });
    1949           12 :             part_downloads.spawn(
    1950           12 :                 self.load_timeline_metadata(
    1951           12 :                     timeline_id,
    1952           12 :                     remote_storage.clone(),
    1953           12 :                     previous_timeline_heatmap,
    1954           12 :                     cancel_clone,
    1955           12 :                 )
    1956           12 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    1957              :             );
    1958              :         }
    1959              : 
    1960          452 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1961              : 
    1962              :         loop {
    1963          464 :             tokio::select!(
    1964          464 :                 next = part_downloads.join_next() => {
    1965          464 :                     match next {
    1966           12 :                         Some(result) => {
    1967           12 :                             let preload = result.context("join preload task")?;
    1968           12 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1969              :                         },
    1970              :                         None => {
    1971          452 :                             break;
    1972              :                         }
    1973              :                     }
    1974              :                 },
    1975          464 :                 _ = cancel.cancelled() => {
    1976            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1977              :                 }
    1978              :             )
    1979              :         }
    1980              : 
    1981          452 :         Ok(timeline_preloads)
    1982          452 :     }
    1983              : 
    1984           12 :     fn build_timeline_client(
    1985           12 :         &self,
    1986           12 :         timeline_id: TimelineId,
    1987           12 :         remote_storage: GenericRemoteStorage,
    1988           12 :     ) -> RemoteTimelineClient {
    1989           12 :         RemoteTimelineClient::new(
    1990           12 :             remote_storage.clone(),
    1991           12 :             self.deletion_queue_client.clone(),
    1992           12 :             self.conf,
    1993           12 :             self.tenant_shard_id,
    1994           12 :             timeline_id,
    1995           12 :             self.generation,
    1996           12 :             &self.tenant_conf.load().location,
    1997           12 :         )
    1998           12 :     }
    1999              : 
    2000           12 :     fn load_timeline_metadata(
    2001           12 :         self: &Arc<Tenant>,
    2002           12 :         timeline_id: TimelineId,
    2003           12 :         remote_storage: GenericRemoteStorage,
    2004           12 :         previous_heatmap: Option<PreviousHeatmap>,
    2005           12 :         cancel: CancellationToken,
    2006           12 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2007           12 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2008           12 :         async move {
    2009           12 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2010           12 :             debug!("starting index part download");
    2011              : 
    2012           12 :             let index_part = client.download_index_file(&cancel).await;
    2013              : 
    2014           12 :             debug!("finished index part download");
    2015              : 
    2016           12 :             TimelinePreload {
    2017           12 :                 client,
    2018           12 :                 timeline_id,
    2019           12 :                 index_part,
    2020           12 :                 previous_heatmap,
    2021           12 :             }
    2022           12 :         }
    2023           12 :     }
    2024              : 
    2025            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2026            0 :         timeline_id: TimelineId,
    2027            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2028            0 :     ) -> Result<(), TimelineArchivalError> {
    2029            0 :         let children: Vec<TimelineId> = timelines
    2030            0 :             .iter()
    2031            0 :             .filter_map(|(id, entry)| {
    2032            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2033            0 :                     return None;
    2034            0 :                 }
    2035            0 :                 if entry.is_archived() == Some(true) {
    2036            0 :                     return None;
    2037            0 :                 }
    2038            0 :                 Some(*id)
    2039            0 :             })
    2040            0 :             .collect();
    2041            0 : 
    2042            0 :         if !children.is_empty() {
    2043            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2044            0 :         }
    2045            0 :         Ok(())
    2046            0 :     }
    2047              : 
    2048            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2049            0 :         ancestor_timeline_id: TimelineId,
    2050            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2051            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2052            0 :             '_,
    2053            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2054            0 :         >,
    2055            0 :     ) -> Result<(), TimelineArchivalError> {
    2056            0 :         let has_archived_parent =
    2057            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2058            0 :                 ancestor_timeline.is_archived() == Some(true)
    2059            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2060            0 :                 true
    2061              :             } else {
    2062            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2063            0 :                 if cfg!(debug_assertions) {
    2064            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2065            0 :                 }
    2066            0 :                 return Err(TimelineArchivalError::NotFound);
    2067              :             };
    2068            0 :         if has_archived_parent {
    2069            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2070            0 :                 ancestor_timeline_id,
    2071            0 :             ));
    2072            0 :         }
    2073            0 :         Ok(())
    2074            0 :     }
    2075              : 
    2076            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2077            0 :         timeline: &Arc<Timeline>,
    2078            0 :     ) -> Result<(), TimelineArchivalError> {
    2079            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2080            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2081            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2082            0 :                     ancestor_timeline.timeline_id,
    2083            0 :                 ));
    2084            0 :             }
    2085            0 :         }
    2086            0 :         Ok(())
    2087            0 :     }
    2088              : 
    2089              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2090              :     ///
    2091              :     /// Counterpart to [`offload_timeline`].
    2092            0 :     async fn unoffload_timeline(
    2093            0 :         self: &Arc<Self>,
    2094            0 :         timeline_id: TimelineId,
    2095            0 :         broker_client: storage_broker::BrokerClientChannel,
    2096            0 :         ctx: RequestContext,
    2097            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2098            0 :         info!("unoffloading timeline");
    2099              : 
    2100              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2101              :         // We expect callers of this function to ensure this.
    2102            0 :         match self.current_state() {
    2103              :             TenantState::Activating { .. }
    2104              :             | TenantState::Attaching
    2105              :             | TenantState::Broken { .. } => {
    2106            0 :                 panic!("Timeline expected to be active")
    2107              :             }
    2108            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2109            0 :             TenantState::Active => {}
    2110            0 :         }
    2111            0 :         let cancel = self.cancel.clone();
    2112            0 : 
    2113            0 :         // Protect against concurrent attempts to use this TimelineId
    2114            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2115            0 :         let allow_offloaded = true;
    2116            0 :         let _create_guard = self
    2117            0 :             .create_timeline_create_guard(
    2118            0 :                 timeline_id,
    2119            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2120            0 :                 allow_offloaded,
    2121            0 :             )
    2122            0 :             .map_err(|err| match err {
    2123            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2124              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2125            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2126              :                 }
    2127            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2128            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2129            0 :             })?;
    2130              : 
    2131            0 :         let timeline_preload = self
    2132            0 :             .load_timeline_metadata(
    2133            0 :                 timeline_id,
    2134            0 :                 self.remote_storage.clone(),
    2135            0 :                 None,
    2136            0 :                 cancel.clone(),
    2137            0 :             )
    2138            0 :             .await;
    2139              : 
    2140            0 :         let index_part = match timeline_preload.index_part {
    2141            0 :             Ok(index_part) => {
    2142            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2143            0 :                 index_part
    2144              :             }
    2145              :             Err(DownloadError::NotFound) => {
    2146            0 :                 error!(%timeline_id, "index_part not found on remote");
    2147            0 :                 return Err(TimelineArchivalError::NotFound);
    2148              :             }
    2149            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2150            0 :             Err(e) => {
    2151            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2152            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2153            0 :                 return Err(TimelineArchivalError::Other(
    2154            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2155            0 :                 ));
    2156              :             }
    2157              :         };
    2158            0 :         let index_part = match index_part {
    2159            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2160            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2161            0 :                 info!("timeline is deleted according to index_part.json");
    2162            0 :                 return Err(TimelineArchivalError::NotFound);
    2163              :             }
    2164              :         };
    2165            0 :         let remote_metadata = index_part.metadata.clone();
    2166            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2167            0 :         self.load_remote_timeline(
    2168            0 :             timeline_id,
    2169            0 :             index_part,
    2170            0 :             remote_metadata,
    2171            0 :             None,
    2172            0 :             timeline_resources,
    2173            0 :             LoadTimelineCause::Unoffload,
    2174            0 :             &ctx,
    2175            0 :         )
    2176            0 :         .await
    2177            0 :         .with_context(|| {
    2178            0 :             format!(
    2179            0 :                 "failed to load remote timeline {} for tenant {}",
    2180            0 :                 timeline_id, self.tenant_shard_id
    2181            0 :             )
    2182            0 :         })
    2183            0 :         .map_err(TimelineArchivalError::Other)?;
    2184              : 
    2185            0 :         let timeline = {
    2186            0 :             let timelines = self.timelines.lock().unwrap();
    2187            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2188            0 :                 warn!("timeline not available directly after attach");
    2189              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2190              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2191            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2192            0 :                     "timeline not available directly after attach"
    2193            0 :                 )));
    2194              :             };
    2195            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2196            0 :             match offloaded_timelines.remove(&timeline_id) {
    2197            0 :                 Some(offloaded) => {
    2198            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2199            0 :                 }
    2200            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2201              :             }
    2202              : 
    2203            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2204            0 : 
    2205            0 :             Arc::clone(timeline)
    2206            0 :         };
    2207            0 : 
    2208            0 :         // Upload new list of offloaded timelines to S3
    2209            0 :         self.store_tenant_manifest().await?;
    2210              : 
    2211              :         // Activate the timeline (if it makes sense)
    2212            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2213            0 :             let background_jobs_can_start = None;
    2214            0 :             timeline.activate(
    2215            0 :                 self.clone(),
    2216            0 :                 broker_client.clone(),
    2217            0 :                 background_jobs_can_start,
    2218            0 :                 &ctx,
    2219            0 :             );
    2220            0 :         }
    2221              : 
    2222            0 :         info!("timeline unoffloading complete");
    2223            0 :         Ok(timeline)
    2224            0 :     }
    2225              : 
    2226            0 :     pub(crate) async fn apply_timeline_archival_config(
    2227            0 :         self: &Arc<Self>,
    2228            0 :         timeline_id: TimelineId,
    2229            0 :         new_state: TimelineArchivalState,
    2230            0 :         broker_client: storage_broker::BrokerClientChannel,
    2231            0 :         ctx: RequestContext,
    2232            0 :     ) -> Result<(), TimelineArchivalError> {
    2233            0 :         info!("setting timeline archival config");
    2234              :         // First part: figure out what is needed to do, and do validation
    2235            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2236            0 :             let timelines = self.timelines.lock().unwrap();
    2237              : 
    2238            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2239            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2240            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2241            0 :                     return Err(TimelineArchivalError::NotFound);
    2242              :                 };
    2243            0 :                 if new_state == TimelineArchivalState::Archived {
    2244              :                     // It's offloaded already, so nothing to do
    2245            0 :                     return Ok(());
    2246            0 :                 }
    2247            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2248            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2249            0 :                         ancestor_timeline_id,
    2250            0 :                         &timelines,
    2251            0 :                         &offloaded_timelines,
    2252            0 :                     )?;
    2253            0 :                 }
    2254            0 :                 break 'outer None;
    2255              :             };
    2256              : 
    2257              :             // Do some validation. We release the timelines lock below, so there is potential
    2258              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2259              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2260            0 :             match new_state {
    2261              :                 TimelineArchivalState::Unarchived => {
    2262            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2263              :                 }
    2264              :                 TimelineArchivalState::Archived => {
    2265            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2266              :                 }
    2267              :             }
    2268            0 :             Some(Arc::clone(timeline))
    2269              :         };
    2270              : 
    2271              :         // Second part: unoffload timeline (if needed)
    2272            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2273            0 :             timeline
    2274              :         } else {
    2275              :             // Turn offloaded timeline into a non-offloaded one
    2276            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2277            0 :                 .await?
    2278              :         };
    2279              : 
    2280              :         // Third part: upload new timeline archival state and block until it is present in S3
    2281            0 :         let upload_needed = match timeline
    2282            0 :             .remote_client
    2283            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2284              :         {
    2285            0 :             Ok(upload_needed) => upload_needed,
    2286            0 :             Err(e) => {
    2287            0 :                 if timeline.cancel.is_cancelled() {
    2288            0 :                     return Err(TimelineArchivalError::Cancelled);
    2289              :                 } else {
    2290            0 :                     return Err(TimelineArchivalError::Other(e));
    2291              :                 }
    2292              :             }
    2293              :         };
    2294              : 
    2295            0 :         if upload_needed {
    2296            0 :             info!("Uploading new state");
    2297              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2298            0 :             let Ok(v) =
    2299            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2300              :             else {
    2301            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2302            0 :                 return Err(TimelineArchivalError::Timeout);
    2303              :             };
    2304            0 :             v.map_err(|e| match e {
    2305            0 :                 WaitCompletionError::NotInitialized(e) => {
    2306            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2307              :                 }
    2308              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2309            0 :                     TimelineArchivalError::Cancelled
    2310              :                 }
    2311            0 :             })?;
    2312            0 :         }
    2313            0 :         Ok(())
    2314            0 :     }
    2315              : 
    2316            4 :     pub fn get_offloaded_timeline(
    2317            4 :         &self,
    2318            4 :         timeline_id: TimelineId,
    2319            4 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2320            4 :         self.timelines_offloaded
    2321            4 :             .lock()
    2322            4 :             .unwrap()
    2323            4 :             .get(&timeline_id)
    2324            4 :             .map(Arc::clone)
    2325            4 :             .ok_or(GetTimelineError::NotFound {
    2326            4 :                 tenant_id: self.tenant_shard_id,
    2327            4 :                 timeline_id,
    2328            4 :             })
    2329            4 :     }
    2330              : 
    2331            8 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2332            8 :         self.tenant_shard_id
    2333            8 :     }
    2334              : 
    2335              :     /// Get Timeline handle for given Neon timeline ID.
    2336              :     /// This function is idempotent. It doesn't change internal state in any way.
    2337          444 :     pub fn get_timeline(
    2338          444 :         &self,
    2339          444 :         timeline_id: TimelineId,
    2340          444 :         active_only: bool,
    2341          444 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2342          444 :         let timelines_accessor = self.timelines.lock().unwrap();
    2343          444 :         let timeline = timelines_accessor
    2344          444 :             .get(&timeline_id)
    2345          444 :             .ok_or(GetTimelineError::NotFound {
    2346          444 :                 tenant_id: self.tenant_shard_id,
    2347          444 :                 timeline_id,
    2348          444 :             })?;
    2349              : 
    2350          440 :         if active_only && !timeline.is_active() {
    2351            0 :             Err(GetTimelineError::NotActive {
    2352            0 :                 tenant_id: self.tenant_shard_id,
    2353            0 :                 timeline_id,
    2354            0 :                 state: timeline.current_state(),
    2355            0 :             })
    2356              :         } else {
    2357          440 :             Ok(Arc::clone(timeline))
    2358              :         }
    2359          444 :     }
    2360              : 
    2361              :     /// Lists timelines the tenant contains.
    2362              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2363            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2364            0 :         self.timelines
    2365            0 :             .lock()
    2366            0 :             .unwrap()
    2367            0 :             .values()
    2368            0 :             .map(Arc::clone)
    2369            0 :             .collect()
    2370            0 :     }
    2371              : 
    2372              :     /// Lists timelines the tenant manages, including offloaded ones.
    2373              :     ///
    2374              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2375            0 :     pub fn list_timelines_and_offloaded(
    2376            0 :         &self,
    2377            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2378            0 :         let timelines = self
    2379            0 :             .timelines
    2380            0 :             .lock()
    2381            0 :             .unwrap()
    2382            0 :             .values()
    2383            0 :             .map(Arc::clone)
    2384            0 :             .collect();
    2385            0 :         let offloaded = self
    2386            0 :             .timelines_offloaded
    2387            0 :             .lock()
    2388            0 :             .unwrap()
    2389            0 :             .values()
    2390            0 :             .map(Arc::clone)
    2391            0 :             .collect();
    2392            0 :         (timelines, offloaded)
    2393            0 :     }
    2394              : 
    2395            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2396            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2397            0 :     }
    2398              : 
    2399              :     /// This is used by tests & import-from-basebackup.
    2400              :     ///
    2401              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2402              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2403              :     ///
    2404              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2405              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2406              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2407              :     /// to the [`Tenant::timelines`].
    2408              :     ///
    2409              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2410          436 :     pub(crate) async fn create_empty_timeline(
    2411          436 :         self: &Arc<Self>,
    2412          436 :         new_timeline_id: TimelineId,
    2413          436 :         initdb_lsn: Lsn,
    2414          436 :         pg_version: u32,
    2415          436 :         _ctx: &RequestContext,
    2416          436 :     ) -> anyhow::Result<UninitializedTimeline> {
    2417          436 :         anyhow::ensure!(
    2418          436 :             self.is_active(),
    2419            0 :             "Cannot create empty timelines on inactive tenant"
    2420              :         );
    2421              : 
    2422              :         // Protect against concurrent attempts to use this TimelineId
    2423          436 :         let create_guard = match self
    2424          436 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2425          436 :             .await?
    2426              :         {
    2427          432 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2428              :             StartCreatingTimelineResult::Idempotent(_) => {
    2429            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2430              :             }
    2431              :         };
    2432              : 
    2433          432 :         let new_metadata = TimelineMetadata::new(
    2434          432 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2435          432 :             // make it valid, before calling finish_creation()
    2436          432 :             Lsn(0),
    2437          432 :             None,
    2438          432 :             None,
    2439          432 :             Lsn(0),
    2440          432 :             initdb_lsn,
    2441          432 :             initdb_lsn,
    2442          432 :             pg_version,
    2443          432 :         );
    2444          432 :         self.prepare_new_timeline(
    2445          432 :             new_timeline_id,
    2446          432 :             &new_metadata,
    2447          432 :             create_guard,
    2448          432 :             initdb_lsn,
    2449          432 :             None,
    2450          432 :         )
    2451          432 :         .await
    2452          436 :     }
    2453              : 
    2454              :     /// Helper for unit tests to create an empty timeline.
    2455              :     ///
    2456              :     /// The timeline is has state value `Active` but its background loops are not running.
    2457              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2458              :     // Our current tests don't need the background loops.
    2459              :     #[cfg(test)]
    2460          416 :     pub async fn create_test_timeline(
    2461          416 :         self: &Arc<Self>,
    2462          416 :         new_timeline_id: TimelineId,
    2463          416 :         initdb_lsn: Lsn,
    2464          416 :         pg_version: u32,
    2465          416 :         ctx: &RequestContext,
    2466          416 :     ) -> anyhow::Result<Arc<Timeline>> {
    2467          416 :         let uninit_tl = self
    2468          416 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2469          416 :             .await?;
    2470          416 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2471          416 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2472              : 
    2473              :         // Setup minimum keys required for the timeline to be usable.
    2474          416 :         let mut modification = tline.begin_modification(initdb_lsn);
    2475          416 :         modification
    2476          416 :             .init_empty_test_timeline()
    2477          416 :             .context("init_empty_test_timeline")?;
    2478          416 :         modification
    2479          416 :             .commit(ctx)
    2480          416 :             .await
    2481          416 :             .context("commit init_empty_test_timeline modification")?;
    2482              : 
    2483              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2484          416 :         tline.maybe_spawn_flush_loop();
    2485          416 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2486              : 
    2487              :         // Make sure the freeze_and_flush reaches remote storage.
    2488          416 :         tline.remote_client.wait_completion().await.unwrap();
    2489              : 
    2490          416 :         let tl = uninit_tl.finish_creation().await?;
    2491              :         // The non-test code would call tl.activate() here.
    2492          416 :         tl.set_state(TimelineState::Active);
    2493          416 :         Ok(tl)
    2494          416 :     }
    2495              : 
    2496              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2497              :     #[cfg(test)]
    2498              :     #[allow(clippy::too_many_arguments)]
    2499           84 :     pub async fn create_test_timeline_with_layers(
    2500           84 :         self: &Arc<Self>,
    2501           84 :         new_timeline_id: TimelineId,
    2502           84 :         initdb_lsn: Lsn,
    2503           84 :         pg_version: u32,
    2504           84 :         ctx: &RequestContext,
    2505           84 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2506           84 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2507           84 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2508           84 :         end_lsn: Lsn,
    2509           84 :     ) -> anyhow::Result<Arc<Timeline>> {
    2510              :         use checks::check_valid_layermap;
    2511              :         use itertools::Itertools;
    2512              : 
    2513           84 :         let tline = self
    2514           84 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2515           84 :             .await?;
    2516           84 :         tline.force_advance_lsn(end_lsn);
    2517          256 :         for deltas in delta_layer_desc {
    2518          172 :             tline
    2519          172 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2520          172 :                 .await?;
    2521              :         }
    2522          204 :         for (lsn, images) in image_layer_desc {
    2523          120 :             tline
    2524          120 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2525          120 :                 .await?;
    2526              :         }
    2527           92 :         for in_memory in in_memory_layer_desc {
    2528            8 :             tline
    2529            8 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2530            8 :                 .await?;
    2531              :         }
    2532           84 :         let layer_names = tline
    2533           84 :             .layers
    2534           84 :             .read()
    2535           84 :             .await
    2536           84 :             .layer_map()
    2537           84 :             .unwrap()
    2538           84 :             .iter_historic_layers()
    2539          376 :             .map(|layer| layer.layer_name())
    2540           84 :             .collect_vec();
    2541           84 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2542            0 :             bail!("invalid layermap: {err}");
    2543           84 :         }
    2544           84 :         Ok(tline)
    2545           84 :     }
    2546              : 
    2547              :     /// Create a new timeline.
    2548              :     ///
    2549              :     /// Returns the new timeline ID and reference to its Timeline object.
    2550              :     ///
    2551              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2552              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2553              :     #[allow(clippy::too_many_arguments)]
    2554            0 :     pub(crate) async fn create_timeline(
    2555            0 :         self: &Arc<Tenant>,
    2556            0 :         params: CreateTimelineParams,
    2557            0 :         broker_client: storage_broker::BrokerClientChannel,
    2558            0 :         ctx: &RequestContext,
    2559            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2560            0 :         if !self.is_active() {
    2561            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2562            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2563              :             } else {
    2564            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2565            0 :                     "Cannot create timelines on inactive tenant"
    2566            0 :                 )));
    2567              :             }
    2568            0 :         }
    2569              : 
    2570            0 :         let _gate = self
    2571            0 :             .gate
    2572            0 :             .enter()
    2573            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2574              : 
    2575            0 :         let result: CreateTimelineResult = match params {
    2576              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2577            0 :                 new_timeline_id,
    2578            0 :                 existing_initdb_timeline_id,
    2579            0 :                 pg_version,
    2580            0 :             }) => {
    2581            0 :                 self.bootstrap_timeline(
    2582            0 :                     new_timeline_id,
    2583            0 :                     pg_version,
    2584            0 :                     existing_initdb_timeline_id,
    2585            0 :                     ctx,
    2586            0 :                 )
    2587            0 :                 .await?
    2588              :             }
    2589              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2590            0 :                 new_timeline_id,
    2591            0 :                 ancestor_timeline_id,
    2592            0 :                 mut ancestor_start_lsn,
    2593              :             }) => {
    2594            0 :                 let ancestor_timeline = self
    2595            0 :                     .get_timeline(ancestor_timeline_id, false)
    2596            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2597              : 
    2598              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2599              :                 // ready for other purposes either.
    2600            0 :                 if !ancestor_timeline.is_active() {
    2601            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2602            0 :                 }
    2603            0 : 
    2604            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2605            0 :                     info!("tried to branch archived timeline");
    2606            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2607            0 :                 }
    2608              : 
    2609            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2610            0 :                     *lsn = lsn.align();
    2611            0 : 
    2612            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2613            0 :                     if ancestor_ancestor_lsn > *lsn {
    2614              :                         // can we safely just branch from the ancestor instead?
    2615            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2616            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2617            0 :                             lsn,
    2618            0 :                             ancestor_timeline_id,
    2619            0 :                             ancestor_ancestor_lsn,
    2620            0 :                         )));
    2621            0 :                     }
    2622            0 : 
    2623            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2624            0 :                     // to the requested branch point. The repository code itself doesn't
    2625            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2626            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2627            0 :                     // sizes etc. and that would get confused if the previous page versions
    2628            0 :                     // are not in the repository yet.
    2629            0 :                     ancestor_timeline
    2630            0 :                         .wait_lsn(
    2631            0 :                             *lsn,
    2632            0 :                             timeline::WaitLsnWaiter::Tenant,
    2633            0 :                             timeline::WaitLsnTimeout::Default,
    2634            0 :                             ctx,
    2635            0 :                         )
    2636            0 :                         .await
    2637            0 :                         .map_err(|e| match e {
    2638            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2639            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2640              :                             }
    2641            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2642            0 :                         })?;
    2643            0 :                 }
    2644              : 
    2645            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2646            0 :                     .await?
    2647              :             }
    2648            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2649            0 :                 self.create_timeline_import_pgdata(
    2650            0 :                     params,
    2651            0 :                     ActivateTimelineArgs::Yes {
    2652            0 :                         broker_client: broker_client.clone(),
    2653            0 :                     },
    2654            0 :                     ctx,
    2655            0 :                 )
    2656            0 :                 .await?
    2657              :             }
    2658              :         };
    2659              : 
    2660              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2661              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2662              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2663              :         //
    2664              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2665              :         // assume that, because they can see the timeline via API, that the creation is done and
    2666              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2667              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2668              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2669              :         //
    2670              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2671              :         // creation API until it returns success. Only then is durability guaranteed.
    2672            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2673            0 :         result
    2674            0 :             .timeline()
    2675            0 :             .remote_client
    2676            0 :             .wait_completion()
    2677            0 :             .await
    2678            0 :             .map_err(|e| match e {
    2679              :                 WaitCompletionError::NotInitialized(
    2680            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2681            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2682              :                 WaitCompletionError::NotInitialized(_) => {
    2683              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2684            0 :                     debug_assert!(false);
    2685            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2686              :                 }
    2687              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2688            0 :                     CreateTimelineError::ShuttingDown
    2689              :                 }
    2690            0 :             })?;
    2691              : 
    2692              :         // The creating task is responsible for activating the timeline.
    2693              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2694              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2695            0 :         let activated_timeline = match result {
    2696            0 :             CreateTimelineResult::Created(timeline) => {
    2697            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2698            0 :                 timeline
    2699              :             }
    2700            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2701            0 :                 info!(
    2702            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2703              :                 );
    2704            0 :                 timeline
    2705              :             }
    2706            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2707            0 :                 info!(
    2708            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2709              :                 );
    2710            0 :                 timeline
    2711              :             }
    2712              :         };
    2713              : 
    2714            0 :         Ok(activated_timeline)
    2715            0 :     }
    2716              : 
    2717              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2718              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2719              :     /// [`Tenant::timelines`] map when the import completes.
    2720              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2721              :     /// for the response.
    2722            0 :     async fn create_timeline_import_pgdata(
    2723            0 :         self: &Arc<Tenant>,
    2724            0 :         params: CreateTimelineParamsImportPgdata,
    2725            0 :         activate: ActivateTimelineArgs,
    2726            0 :         ctx: &RequestContext,
    2727            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2728            0 :         let CreateTimelineParamsImportPgdata {
    2729            0 :             new_timeline_id,
    2730            0 :             location,
    2731            0 :             idempotency_key,
    2732            0 :         } = params;
    2733            0 : 
    2734            0 :         let started_at = chrono::Utc::now().naive_utc();
    2735              : 
    2736              :         //
    2737              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2738              :         // is the canonical way we do it.
    2739              :         // - create an empty timeline in-memory
    2740              :         // - use its remote_timeline_client to do the upload
    2741              :         // - dispose of the uninit timeline
    2742              :         // - keep the creation guard alive
    2743              : 
    2744            0 :         let timeline_create_guard = match self
    2745            0 :             .start_creating_timeline(
    2746            0 :                 new_timeline_id,
    2747            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2748            0 :                     idempotency_key: idempotency_key.clone(),
    2749            0 :                 }),
    2750            0 :             )
    2751            0 :             .await?
    2752              :         {
    2753            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2754            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2755            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2756              :             }
    2757              :         };
    2758              : 
    2759            0 :         let mut uninit_timeline = {
    2760            0 :             let this = &self;
    2761            0 :             let initdb_lsn = Lsn(0);
    2762            0 :             let _ctx = ctx;
    2763            0 :             async move {
    2764            0 :                 let new_metadata = TimelineMetadata::new(
    2765            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2766            0 :                     // make it valid, before calling finish_creation()
    2767            0 :                     Lsn(0),
    2768            0 :                     None,
    2769            0 :                     None,
    2770            0 :                     Lsn(0),
    2771            0 :                     initdb_lsn,
    2772            0 :                     initdb_lsn,
    2773            0 :                     15,
    2774            0 :                 );
    2775            0 :                 this.prepare_new_timeline(
    2776            0 :                     new_timeline_id,
    2777            0 :                     &new_metadata,
    2778            0 :                     timeline_create_guard,
    2779            0 :                     initdb_lsn,
    2780            0 :                     None,
    2781            0 :                 )
    2782            0 :                 .await
    2783            0 :             }
    2784            0 :         }
    2785            0 :         .await?;
    2786              : 
    2787            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2788            0 :             idempotency_key,
    2789            0 :             location,
    2790            0 :             started_at,
    2791            0 :         };
    2792            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2793            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2794            0 :         );
    2795            0 :         uninit_timeline
    2796            0 :             .raw_timeline()
    2797            0 :             .unwrap()
    2798            0 :             .remote_client
    2799            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2800              : 
    2801              :         // wait_completion happens in caller
    2802              : 
    2803            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2804            0 : 
    2805            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2806            0 :             timeline.clone(),
    2807            0 :             index_part,
    2808            0 :             activate,
    2809            0 :             timeline_create_guard,
    2810            0 :         ));
    2811            0 : 
    2812            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2813            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2814            0 :     }
    2815              : 
    2816              :     #[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))]
    2817              :     async fn create_timeline_import_pgdata_task(
    2818              :         self: Arc<Tenant>,
    2819              :         timeline: Arc<Timeline>,
    2820              :         index_part: import_pgdata::index_part_format::Root,
    2821              :         activate: ActivateTimelineArgs,
    2822              :         timeline_create_guard: TimelineCreateGuard,
    2823              :     ) {
    2824              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2825              :         info!("starting");
    2826              :         scopeguard::defer! {info!("exiting")};
    2827              : 
    2828              :         let res = self
    2829              :             .create_timeline_import_pgdata_task_impl(
    2830              :                 timeline,
    2831              :                 index_part,
    2832              :                 activate,
    2833              :                 timeline_create_guard,
    2834              :             )
    2835              :             .await;
    2836              :         if let Err(err) = &res {
    2837              :             error!(?err, "task failed");
    2838              :             // TODO sleep & retry, sensitive to tenant shutdown
    2839              :             // TODO: allow timeline deletion requests => should cancel the task
    2840              :         }
    2841              :     }
    2842              : 
    2843            0 :     async fn create_timeline_import_pgdata_task_impl(
    2844            0 :         self: Arc<Tenant>,
    2845            0 :         timeline: Arc<Timeline>,
    2846            0 :         index_part: import_pgdata::index_part_format::Root,
    2847            0 :         activate: ActivateTimelineArgs,
    2848            0 :         timeline_create_guard: TimelineCreateGuard,
    2849            0 :     ) -> Result<(), anyhow::Error> {
    2850            0 :         let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
    2851            0 : 
    2852            0 :         info!("importing pgdata");
    2853            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2854            0 :             .await
    2855            0 :             .context("import")?;
    2856            0 :         info!("import done");
    2857              : 
    2858              :         //
    2859              :         // Reload timeline from remote.
    2860              :         // This proves that the remote state is attachable, and it reuses the code.
    2861              :         //
    2862              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2863              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2864              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2865              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2866              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2867              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2868              :         // to manifest because of the long runtime of this import task.
    2869              : 
    2870              :         //        in theory this shouldn't even .await anything except for coop yield
    2871            0 :         info!("shutting down timeline");
    2872            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2873            0 :         info!("timeline shut down, reloading from remote");
    2874              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2875              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2876              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2877              :         // };
    2878            0 :         let timeline_id = timeline.timeline_id;
    2879            0 : 
    2880            0 :         // load from object storage like Tenant::attach does
    2881            0 :         let resources = self.build_timeline_resources(timeline_id);
    2882            0 :         let index_part = resources
    2883            0 :             .remote_client
    2884            0 :             .download_index_file(&self.cancel)
    2885            0 :             .await?;
    2886            0 :         let index_part = match index_part {
    2887              :             MaybeDeletedIndexPart::Deleted(_) => {
    2888              :                 // likely concurrent delete call, cplane should prevent this
    2889            0 :                 anyhow::bail!(
    2890            0 :                     "index part says deleted but we are not done creating yet, this should not happen but"
    2891            0 :                 )
    2892              :             }
    2893            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2894            0 :         };
    2895            0 :         let metadata = index_part.metadata.clone();
    2896            0 :         self
    2897            0 :             .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
    2898            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2899            0 :             .await?
    2900            0 :             .ready_to_activate()
    2901            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2902              : 
    2903            0 :         anyhow::Ok(())
    2904            0 :     }
    2905              : 
    2906            0 :     pub(crate) async fn delete_timeline(
    2907            0 :         self: Arc<Self>,
    2908            0 :         timeline_id: TimelineId,
    2909            0 :     ) -> Result<(), DeleteTimelineError> {
    2910            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2911              : 
    2912            0 :         Ok(())
    2913            0 :     }
    2914              : 
    2915              :     /// perform one garbage collection iteration, removing old data files from disk.
    2916              :     /// this function is periodically called by gc task.
    2917              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2918              :     ///
    2919              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2920              :     ///
    2921              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2922              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2923              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2924              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2925              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2926              :     /// requires more history to be retained.
    2927              :     //
    2928         1508 :     pub(crate) async fn gc_iteration(
    2929         1508 :         &self,
    2930         1508 :         target_timeline_id: Option<TimelineId>,
    2931         1508 :         horizon: u64,
    2932         1508 :         pitr: Duration,
    2933         1508 :         cancel: &CancellationToken,
    2934         1508 :         ctx: &RequestContext,
    2935         1508 :     ) -> Result<GcResult, GcError> {
    2936         1508 :         // Don't start doing work during shutdown
    2937         1508 :         if let TenantState::Stopping { .. } = self.current_state() {
    2938            0 :             return Ok(GcResult::default());
    2939         1508 :         }
    2940         1508 : 
    2941         1508 :         // there is a global allowed_error for this
    2942         1508 :         if !self.is_active() {
    2943            0 :             return Err(GcError::NotActive);
    2944         1508 :         }
    2945         1508 : 
    2946         1508 :         {
    2947         1508 :             let conf = self.tenant_conf.load();
    2948         1508 : 
    2949         1508 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2950         1508 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2951         1508 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2952         1508 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2953         1508 :             if !conf.location.may_delete_layers_hint() {
    2954            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2955            0 :                 return Ok(GcResult::default());
    2956         1508 :             }
    2957         1508 : 
    2958         1508 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2959         1500 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2960         1500 :                 return Ok(GcResult::default());
    2961            8 :             }
    2962              :         }
    2963              : 
    2964            8 :         let _guard = match self.gc_block.start().await {
    2965            8 :             Ok(guard) => guard,
    2966            0 :             Err(reasons) => {
    2967            0 :                 info!("Skipping GC: {reasons}");
    2968            0 :                 return Ok(GcResult::default());
    2969              :             }
    2970              :         };
    2971              : 
    2972            8 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2973            8 :             .await
    2974         1508 :     }
    2975              : 
    2976              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    2977              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    2978              :     /// immediate L0 compaction.
    2979              :     ///
    2980              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    2981            0 :     async fn compaction_iteration(
    2982            0 :         self: &Arc<Self>,
    2983            0 :         cancel: &CancellationToken,
    2984            0 :         ctx: &RequestContext,
    2985            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    2986            0 :         // Don't compact inactive tenants.
    2987            0 :         if !self.is_active() {
    2988            0 :             return Ok(CompactionOutcome::Skipped);
    2989            0 :         }
    2990            0 : 
    2991            0 :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    2992            0 :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    2993            0 :         let location = self.tenant_conf.load().location;
    2994            0 :         if !location.may_upload_layers_hint() {
    2995            0 :             info!("skipping compaction in location state {location:?}");
    2996            0 :             return Ok(CompactionOutcome::Skipped);
    2997            0 :         }
    2998            0 : 
    2999            0 :         // Don't compact if the circuit breaker is tripped.
    3000            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3001            0 :             info!("skipping compaction due to previous failures");
    3002            0 :             return Ok(CompactionOutcome::Skipped);
    3003            0 :         }
    3004            0 : 
    3005            0 :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3006            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3007            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3008            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3009            0 : 
    3010            0 :         {
    3011            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3012            0 :             let timelines = self.timelines.lock().unwrap();
    3013            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3014              :                 // Skip inactive timelines.
    3015            0 :                 if !timeline.is_active() {
    3016            0 :                     continue;
    3017            0 :                 }
    3018            0 : 
    3019            0 :                 // Schedule the timeline for compaction.
    3020            0 :                 compact.push(timeline.clone());
    3021              : 
    3022              :                 // Schedule the timeline for offloading if eligible.
    3023            0 :                 let can_offload = offload_enabled
    3024            0 :                     && timeline.can_offload().0
    3025            0 :                     && !timelines
    3026            0 :                         .iter()
    3027            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3028            0 :                 if can_offload {
    3029            0 :                     offload.insert(timeline_id);
    3030            0 :                 }
    3031              :             }
    3032              :         } // release timelines lock
    3033              : 
    3034            0 :         for timeline in &compact {
    3035              :             // Collect L0 counts. Can't await while holding lock above.
    3036            0 :             if let Ok(lm) = timeline.layers.read().await.layer_map() {
    3037            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3038            0 :             }
    3039              :         }
    3040              : 
    3041              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3042              :         // bound read amplification.
    3043              :         //
    3044              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3045              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3046              :         // splitting L0 and image/GC compaction to separate background jobs.
    3047            0 :         if self.get_compaction_l0_first() {
    3048            0 :             let compaction_threshold = self.get_compaction_threshold();
    3049            0 :             let compact_l0 = compact
    3050            0 :                 .iter()
    3051            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3052            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3053            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3054            0 :                 .rev()
    3055            0 :                 .map(|(tli, _)| tli.clone())
    3056            0 :                 .collect_vec();
    3057            0 : 
    3058            0 :             let mut has_pending_l0 = false;
    3059            0 :             for timeline in compact_l0 {
    3060            0 :                 let outcome = timeline
    3061            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3062            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3063            0 :                     .await
    3064            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3065            0 :                 match outcome {
    3066            0 :                     CompactionOutcome::Done => {}
    3067            0 :                     CompactionOutcome::Skipped => {}
    3068            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3069            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3070              :                 }
    3071              :             }
    3072            0 :             if has_pending_l0 {
    3073            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3074            0 :             }
    3075            0 :         }
    3076              : 
    3077              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated
    3078              :         // more L0 layers, they may also be compacted here.
    3079              :         //
    3080              :         // NB: image compaction may yield if there is pending L0 compaction.
    3081              :         //
    3082              :         // TODO: it will only yield if there is pending L0 compaction on the same timeline. If a
    3083              :         // different timeline needs compaction, it won't. It should check `l0_compaction_trigger`.
    3084              :         // We leave this for a later PR.
    3085              :         //
    3086              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3087              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3088            0 :         let mut has_pending = false;
    3089            0 :         for timeline in compact {
    3090            0 :             if !timeline.is_active() {
    3091            0 :                 continue;
    3092            0 :             }
    3093              : 
    3094            0 :             let mut outcome = timeline
    3095            0 :                 .compact(cancel, EnumSet::default(), ctx)
    3096            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3097            0 :                 .await
    3098            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3099              : 
    3100              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3101            0 :             if outcome == CompactionOutcome::Done {
    3102            0 :                 let queue = {
    3103            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3104            0 :                     guard
    3105            0 :                         .entry(timeline.timeline_id)
    3106            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3107            0 :                         .clone()
    3108            0 :                 };
    3109            0 :                 outcome = queue
    3110            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3111            0 :                     .instrument(
    3112            0 :                         info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
    3113              :                     )
    3114            0 :                     .await?;
    3115            0 :             }
    3116              : 
    3117              :             // If we're done compacting, offload the timeline if requested.
    3118            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3119            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3120            0 :                 offload_timeline(self, &timeline)
    3121            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3122            0 :                     .await
    3123            0 :                     .or_else(|err| match err {
    3124              :                         // Ignore this, we likely raced with unarchival.
    3125            0 :                         OffloadError::NotArchived => Ok(()),
    3126            0 :                         err => Err(err),
    3127            0 :                     })?;
    3128            0 :             }
    3129              : 
    3130            0 :             match outcome {
    3131            0 :                 CompactionOutcome::Done => {}
    3132            0 :                 CompactionOutcome::Skipped => {}
    3133            0 :                 CompactionOutcome::Pending => has_pending = true,
    3134              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3135              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3136            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3137              :             }
    3138              :         }
    3139              : 
    3140              :         // Success! Untrip the breaker if necessary.
    3141            0 :         self.compaction_circuit_breaker
    3142            0 :             .lock()
    3143            0 :             .unwrap()
    3144            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3145            0 : 
    3146            0 :         match has_pending {
    3147            0 :             true => Ok(CompactionOutcome::Pending),
    3148            0 :             false => Ok(CompactionOutcome::Done),
    3149              :         }
    3150            0 :     }
    3151              : 
    3152              :     /// Trips the compaction circuit breaker if appropriate.
    3153            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3154            0 :         match err {
    3155            0 :             err if err.is_cancel() => {}
    3156            0 :             CompactionError::ShuttingDown => (),
    3157              :             // Offload failures don't trip the circuit breaker, since they're cheap to retry and
    3158              :             // shouldn't block compaction.
    3159            0 :             CompactionError::Offload(_) => {}
    3160            0 :             CompactionError::CollectKeySpaceError(err) => {
    3161            0 :                 // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
    3162            0 :                 self.compaction_circuit_breaker
    3163            0 :                     .lock()
    3164            0 :                     .unwrap()
    3165            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3166            0 :             }
    3167            0 :             CompactionError::Other(err) => {
    3168            0 :                 self.compaction_circuit_breaker
    3169            0 :                     .lock()
    3170            0 :                     .unwrap()
    3171            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3172            0 :             }
    3173            0 :             CompactionError::AlreadyRunning(_) => {}
    3174              :         }
    3175            0 :     }
    3176              : 
    3177              :     /// Cancel scheduled compaction tasks
    3178            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3179            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3180            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3181            0 :             q.cancel_scheduled();
    3182            0 :         }
    3183            0 :     }
    3184              : 
    3185            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3186            0 :         &self,
    3187            0 :         timeline_id: TimelineId,
    3188            0 :     ) -> Vec<CompactInfoResponse> {
    3189            0 :         let res = {
    3190            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3191            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3192              :         };
    3193            0 :         let Some((running, remaining)) = res else {
    3194            0 :             return Vec::new();
    3195              :         };
    3196            0 :         let mut result = Vec::new();
    3197            0 :         if let Some((id, running)) = running {
    3198            0 :             result.extend(running.into_compact_info_resp(id, true));
    3199            0 :         }
    3200            0 :         for (id, job) in remaining {
    3201            0 :             result.extend(job.into_compact_info_resp(id, false));
    3202            0 :         }
    3203            0 :         result
    3204            0 :     }
    3205              : 
    3206              :     /// Schedule a compaction task for a timeline.
    3207            0 :     pub(crate) async fn schedule_compaction(
    3208            0 :         &self,
    3209            0 :         timeline_id: TimelineId,
    3210            0 :         options: CompactOptions,
    3211            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3212            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3213            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3214            0 :         let q = guard
    3215            0 :             .entry(timeline_id)
    3216            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3217            0 :         q.schedule_manual_compaction(options, Some(tx));
    3218            0 :         Ok(rx)
    3219            0 :     }
    3220              : 
    3221              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3222            0 :     async fn housekeeping(&self) {
    3223            0 :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3224            0 :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3225            0 :         let timelines = self
    3226            0 :             .timelines
    3227            0 :             .lock()
    3228            0 :             .unwrap()
    3229            0 :             .values()
    3230            0 :             .filter(|tli| tli.is_active())
    3231            0 :             .cloned()
    3232            0 :             .collect_vec();
    3233              : 
    3234            0 :         for timeline in timelines {
    3235            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3236              :         }
    3237              : 
    3238              :         // Shut down walredo if idle.
    3239              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3240            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3241            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3242            0 :         }
    3243            0 :     }
    3244              : 
    3245            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3246            0 :         let timelines = self.timelines.lock().unwrap();
    3247            0 :         !timelines
    3248            0 :             .iter()
    3249            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3250            0 :     }
    3251              : 
    3252         3476 :     pub fn current_state(&self) -> TenantState {
    3253         3476 :         self.state.borrow().clone()
    3254         3476 :     }
    3255              : 
    3256         1952 :     pub fn is_active(&self) -> bool {
    3257         1952 :         self.current_state() == TenantState::Active
    3258         1952 :     }
    3259              : 
    3260            0 :     pub fn generation(&self) -> Generation {
    3261            0 :         self.generation
    3262            0 :     }
    3263              : 
    3264            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3265            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3266            0 :     }
    3267              : 
    3268              :     /// Changes tenant status to active, unless shutdown was already requested.
    3269              :     ///
    3270              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3271              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3272            0 :     fn activate(
    3273            0 :         self: &Arc<Self>,
    3274            0 :         broker_client: BrokerClientChannel,
    3275            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3276            0 :         ctx: &RequestContext,
    3277            0 :     ) {
    3278            0 :         span::debug_assert_current_span_has_tenant_id();
    3279            0 : 
    3280            0 :         let mut activating = false;
    3281            0 :         self.state.send_modify(|current_state| {
    3282              :             use pageserver_api::models::ActivatingFrom;
    3283            0 :             match &*current_state {
    3284              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3285            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3286              :                 }
    3287            0 :                 TenantState::Attaching => {
    3288            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3289            0 :                 }
    3290            0 :             }
    3291            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3292            0 :             activating = true;
    3293            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3294            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3295            0 :         });
    3296            0 : 
    3297            0 :         if activating {
    3298            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3299            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3300            0 :             let timelines_to_activate = timelines_accessor
    3301            0 :                 .values()
    3302            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3303            0 : 
    3304            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3305            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3306            0 : 
    3307            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3308            0 :             // down when they notice that the tenant is inactive.
    3309            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3310            0 : 
    3311            0 :             let mut activated_timelines = 0;
    3312              : 
    3313            0 :             for timeline in timelines_to_activate {
    3314            0 :                 timeline.activate(
    3315            0 :                     self.clone(),
    3316            0 :                     broker_client.clone(),
    3317            0 :                     background_jobs_can_start,
    3318            0 :                     ctx,
    3319            0 :                 );
    3320            0 :                 activated_timelines += 1;
    3321            0 :             }
    3322              : 
    3323            0 :             self.state.send_modify(move |current_state| {
    3324            0 :                 assert!(
    3325            0 :                     matches!(current_state, TenantState::Activating(_)),
    3326            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3327              :                 );
    3328            0 :                 *current_state = TenantState::Active;
    3329            0 : 
    3330            0 :                 let elapsed = self.constructed_at.elapsed();
    3331            0 :                 let total_timelines = timelines_accessor.len();
    3332            0 : 
    3333            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3334            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3335            0 :                 info!(
    3336            0 :                     since_creation_millis = elapsed.as_millis(),
    3337            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3338            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3339            0 :                     activated_timelines,
    3340            0 :                     total_timelines,
    3341            0 :                     post_state = <&'static str>::from(&*current_state),
    3342            0 :                     "activation attempt finished"
    3343              :                 );
    3344              : 
    3345            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3346            0 :             });
    3347            0 :         }
    3348            0 :     }
    3349              : 
    3350              :     /// Shutdown the tenant and join all of the spawned tasks.
    3351              :     ///
    3352              :     /// The method caters for all use-cases:
    3353              :     /// - pageserver shutdown (freeze_and_flush == true)
    3354              :     /// - detach + ignore (freeze_and_flush == false)
    3355              :     ///
    3356              :     /// This will attempt to shutdown even if tenant is broken.
    3357              :     ///
    3358              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3359              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3360              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3361              :     /// the ongoing shutdown.
    3362           12 :     async fn shutdown(
    3363           12 :         &self,
    3364           12 :         shutdown_progress: completion::Barrier,
    3365           12 :         shutdown_mode: timeline::ShutdownMode,
    3366           12 :     ) -> Result<(), completion::Barrier> {
    3367           12 :         span::debug_assert_current_span_has_tenant_id();
    3368              : 
    3369              :         // Set tenant (and its timlines) to Stoppping state.
    3370              :         //
    3371              :         // Since we can only transition into Stopping state after activation is complete,
    3372              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3373              :         //
    3374              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3375              :         // 1. Lock out any new requests to the tenants.
    3376              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3377              :         // 3. Signal cancellation for other tenant background loops.
    3378              :         // 4. ???
    3379              :         //
    3380              :         // The waiting for the cancellation is not done uniformly.
    3381              :         // We certainly wait for WAL receivers to shut down.
    3382              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3383              :         // But the tenant background loops are joined-on in our caller.
    3384              :         // It's mesed up.
    3385              :         // we just ignore the failure to stop
    3386              : 
    3387              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3388              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3389              :         // is very slow.
    3390           12 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3391            0 :             self.cancel.cancel();
    3392            0 : 
    3393            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3394            0 :             // are children of ours, so their flush loops will have shut down already
    3395            0 :             timeline::ShutdownMode::Hard
    3396              :         } else {
    3397           12 :             shutdown_mode
    3398              :         };
    3399              : 
    3400           12 :         match self.set_stopping(shutdown_progress, false, false).await {
    3401           12 :             Ok(()) => {}
    3402            0 :             Err(SetStoppingError::Broken) => {
    3403            0 :                 // assume that this is acceptable
    3404            0 :             }
    3405            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3406            0 :                 // give caller the option to wait for this this shutdown
    3407            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3408            0 :                 return Err(other);
    3409              :             }
    3410              :         };
    3411              : 
    3412           12 :         let mut js = tokio::task::JoinSet::new();
    3413           12 :         {
    3414           12 :             let timelines = self.timelines.lock().unwrap();
    3415           12 :             timelines.values().for_each(|timeline| {
    3416           12 :                 let timeline = Arc::clone(timeline);
    3417           12 :                 let timeline_id = timeline.timeline_id;
    3418           12 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3419           12 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3420           12 :             });
    3421           12 :         }
    3422           12 :         {
    3423           12 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3424           12 :             timelines_offloaded.values().for_each(|timeline| {
    3425            0 :                 timeline.defuse_for_tenant_drop();
    3426           12 :             });
    3427           12 :         }
    3428           12 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3429           12 :         tracing::info!("Waiting for timelines...");
    3430           24 :         while let Some(res) = js.join_next().await {
    3431            0 :             match res {
    3432           12 :                 Ok(()) => {}
    3433            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3434            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3435            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3436              :             }
    3437              :         }
    3438              : 
    3439           12 :         if let ShutdownMode::Reload = shutdown_mode {
    3440            0 :             tracing::info!("Flushing deletion queue");
    3441            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3442            0 :                 match e {
    3443            0 :                     DeletionQueueError::ShuttingDown => {
    3444            0 :                         // This is the only error we expect for now. In the future, if more error
    3445            0 :                         // variants are added, we should handle them here.
    3446            0 :                     }
    3447              :                 }
    3448            0 :             }
    3449           12 :         }
    3450              : 
    3451              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3452              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3453           12 :         tracing::debug!("Cancelling CancellationToken");
    3454           12 :         self.cancel.cancel();
    3455           12 : 
    3456           12 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3457           12 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3458           12 :         //
    3459           12 :         // this will additionally shutdown and await all timeline tasks.
    3460           12 :         tracing::debug!("Waiting for tasks...");
    3461           12 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3462              : 
    3463           12 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3464           12 :             walredo_mgr.shutdown().await;
    3465            0 :         }
    3466              : 
    3467              :         // Wait for any in-flight operations to complete
    3468           12 :         self.gate.close().await;
    3469              : 
    3470           12 :         remove_tenant_metrics(&self.tenant_shard_id);
    3471           12 : 
    3472           12 :         Ok(())
    3473           12 :     }
    3474              : 
    3475              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3476              :     ///
    3477              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3478              :     ///
    3479              :     /// This function is not cancel-safe!
    3480              :     ///
    3481              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3482              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3483           12 :     async fn set_stopping(
    3484           12 :         &self,
    3485           12 :         progress: completion::Barrier,
    3486           12 :         _allow_transition_from_loading: bool,
    3487           12 :         allow_transition_from_attaching: bool,
    3488           12 :     ) -> Result<(), SetStoppingError> {
    3489           12 :         let mut rx = self.state.subscribe();
    3490           12 : 
    3491           12 :         // cannot stop before we're done activating, so wait out until we're done activating
    3492           12 :         rx.wait_for(|state| match state {
    3493            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3494              :             TenantState::Activating(_) | TenantState::Attaching => {
    3495            0 :                 info!(
    3496            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3497            0 :                     <&'static str>::from(state)
    3498              :                 );
    3499            0 :                 false
    3500              :             }
    3501           12 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3502           12 :         })
    3503           12 :         .await
    3504           12 :         .expect("cannot drop self.state while on a &self method");
    3505           12 : 
    3506           12 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3507           12 :         let mut err = None;
    3508           12 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3509              :             TenantState::Activating(_) => {
    3510            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3511              :             }
    3512              :             TenantState::Attaching => {
    3513            0 :                 if !allow_transition_from_attaching {
    3514            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3515            0 :                 };
    3516            0 :                 *current_state = TenantState::Stopping { progress };
    3517            0 :                 true
    3518              :             }
    3519              :             TenantState::Active => {
    3520              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3521              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3522              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3523           12 :                 *current_state = TenantState::Stopping { progress };
    3524           12 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3525           12 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3526           12 :                 true
    3527              :             }
    3528            0 :             TenantState::Broken { reason, .. } => {
    3529            0 :                 info!(
    3530            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3531              :                 );
    3532            0 :                 err = Some(SetStoppingError::Broken);
    3533            0 :                 false
    3534              :             }
    3535            0 :             TenantState::Stopping { progress } => {
    3536            0 :                 info!("Tenant is already in Stopping state");
    3537            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3538            0 :                 false
    3539              :             }
    3540           12 :         });
    3541           12 :         match (stopping, err) {
    3542           12 :             (true, None) => {} // continue
    3543            0 :             (false, Some(err)) => return Err(err),
    3544            0 :             (true, Some(_)) => unreachable!(
    3545            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3546            0 :             ),
    3547            0 :             (false, None) => unreachable!(
    3548            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3549            0 :             ),
    3550              :         }
    3551              : 
    3552           12 :         let timelines_accessor = self.timelines.lock().unwrap();
    3553           12 :         let not_broken_timelines = timelines_accessor
    3554           12 :             .values()
    3555           12 :             .filter(|timeline| !timeline.is_broken());
    3556           24 :         for timeline in not_broken_timelines {
    3557           12 :             timeline.set_state(TimelineState::Stopping);
    3558           12 :         }
    3559           12 :         Ok(())
    3560           12 :     }
    3561              : 
    3562              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3563              :     /// `remove_tenant_from_memory`
    3564              :     ///
    3565              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3566              :     ///
    3567              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3568            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3569            0 :         let mut rx = self.state.subscribe();
    3570            0 : 
    3571            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3572            0 :         // So, wait until it's done.
    3573            0 :         rx.wait_for(|state| match state {
    3574              :             TenantState::Activating(_) | TenantState::Attaching => {
    3575            0 :                 info!(
    3576            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3577            0 :                     <&'static str>::from(state)
    3578              :                 );
    3579            0 :                 false
    3580              :             }
    3581            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3582            0 :         })
    3583            0 :         .await
    3584            0 :         .expect("cannot drop self.state while on a &self method");
    3585            0 : 
    3586            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3587            0 :         self.set_broken_no_wait(reason)
    3588            0 :     }
    3589              : 
    3590            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3591            0 :         let reason = reason.to_string();
    3592            0 :         self.state.send_modify(|current_state| {
    3593            0 :             match *current_state {
    3594              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3595            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3596              :                 }
    3597              :                 TenantState::Active => {
    3598            0 :                     if cfg!(feature = "testing") {
    3599            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3600            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3601              :                     } else {
    3602            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3603              :                     }
    3604              :                 }
    3605              :                 TenantState::Broken { .. } => {
    3606            0 :                     warn!("Tenant is already in Broken state");
    3607              :                 }
    3608              :                 // This is the only "expected" path, any other path is a bug.
    3609              :                 TenantState::Stopping { .. } => {
    3610            0 :                     warn!(
    3611            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3612              :                         reason
    3613              :                     );
    3614            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3615              :                 }
    3616              :            }
    3617            0 :         });
    3618            0 :     }
    3619              : 
    3620            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3621            0 :         self.state.subscribe()
    3622            0 :     }
    3623              : 
    3624              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3625              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3626            0 :     pub(crate) fn activate_now(&self) {
    3627            0 :         self.activate_now_sem.add_permits(1);
    3628            0 :     }
    3629              : 
    3630            0 :     pub(crate) async fn wait_to_become_active(
    3631            0 :         &self,
    3632            0 :         timeout: Duration,
    3633            0 :     ) -> Result<(), GetActiveTenantError> {
    3634            0 :         let mut receiver = self.state.subscribe();
    3635              :         loop {
    3636            0 :             let current_state = receiver.borrow_and_update().clone();
    3637            0 :             match current_state {
    3638              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3639              :                     // in these states, there's a chance that we can reach ::Active
    3640            0 :                     self.activate_now();
    3641            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3642            0 :                         Ok(r) => {
    3643            0 :                             r.map_err(
    3644            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3645              :                                 // Tenant existed but was dropped: report it as non-existent
    3646            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3647            0 :                         )?
    3648              :                         }
    3649              :                         Err(TimeoutCancellableError::Cancelled) => {
    3650            0 :                             return Err(GetActiveTenantError::Cancelled);
    3651              :                         }
    3652              :                         Err(TimeoutCancellableError::Timeout) => {
    3653            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3654            0 :                                 latest_state: Some(self.current_state()),
    3655            0 :                                 wait_time: timeout,
    3656            0 :                             });
    3657              :                         }
    3658              :                     }
    3659              :                 }
    3660              :                 TenantState::Active { .. } => {
    3661            0 :                     return Ok(());
    3662              :                 }
    3663            0 :                 TenantState::Broken { reason, .. } => {
    3664            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3665            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3666            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3667              :                 }
    3668              :                 TenantState::Stopping { .. } => {
    3669              :                     // There's no chance the tenant can transition back into ::Active
    3670            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3671              :                 }
    3672              :             }
    3673              :         }
    3674            0 :     }
    3675              : 
    3676            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3677            0 :         self.tenant_conf.load().location.attach_mode
    3678            0 :     }
    3679              : 
    3680              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3681              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3682              :     /// rare external API calls, like a reconciliation at startup.
    3683            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3684            0 :         let conf = self.tenant_conf.load();
    3685              : 
    3686            0 :         let location_config_mode = match conf.location.attach_mode {
    3687            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3688            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3689            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3690              :         };
    3691              : 
    3692              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3693            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3694            0 : 
    3695            0 :         models::LocationConfig {
    3696            0 :             mode: location_config_mode,
    3697            0 :             generation: self.generation.into(),
    3698            0 :             secondary_conf: None,
    3699            0 :             shard_number: self.shard_identity.number.0,
    3700            0 :             shard_count: self.shard_identity.count.literal(),
    3701            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3702            0 :             tenant_conf: tenant_config,
    3703            0 :         }
    3704            0 :     }
    3705              : 
    3706            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3707            0 :         &self.tenant_shard_id
    3708            0 :     }
    3709              : 
    3710            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3711            0 :         self.shard_identity.stripe_size
    3712            0 :     }
    3713              : 
    3714            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3715            0 :         self.generation
    3716            0 :     }
    3717              : 
    3718              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3719              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3720              :     /// resetting this tenant to a valid state if we fail.
    3721            0 :     pub(crate) async fn split_prepare(
    3722            0 :         &self,
    3723            0 :         child_shards: &Vec<TenantShardId>,
    3724            0 :     ) -> anyhow::Result<()> {
    3725            0 :         let (timelines, offloaded) = {
    3726            0 :             let timelines = self.timelines.lock().unwrap();
    3727            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3728            0 :             (timelines.clone(), offloaded.clone())
    3729            0 :         };
    3730            0 :         let timelines_iter = timelines
    3731            0 :             .values()
    3732            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3733            0 :             .chain(
    3734            0 :                 offloaded
    3735            0 :                     .values()
    3736            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3737            0 :             );
    3738            0 :         for timeline in timelines_iter {
    3739              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3740              :             // to ensure that they do not start a split if currently in the process of doing these.
    3741              : 
    3742            0 :             let timeline_id = timeline.timeline_id();
    3743              : 
    3744            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3745              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3746              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3747              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3748            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3749            0 :                 timeline
    3750            0 :                     .remote_client
    3751            0 :                     .schedule_index_upload_for_file_changes()?;
    3752            0 :                 timeline.remote_client.wait_completion().await?;
    3753            0 :             }
    3754              : 
    3755            0 :             let remote_client = match timeline {
    3756            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3757            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3758            0 :                     let remote_client = self
    3759            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3760            0 :                     Arc::new(remote_client)
    3761              :                 }
    3762              :             };
    3763              : 
    3764              :             // Shut down the timeline's remote client: this means that the indices we write
    3765              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3766            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3767            0 :             remote_client.shutdown().await;
    3768              : 
    3769              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3770              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3771              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3772              :             // we use here really is the remotely persistent one).
    3773            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3774            0 :             let result = remote_client
    3775            0 :                 .download_index_file(&self.cancel)
    3776            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))
    3777            0 :                 .await?;
    3778            0 :             let index_part = match result {
    3779              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3780            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3781              :                 }
    3782            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3783              :             };
    3784              : 
    3785            0 :             for child_shard in child_shards {
    3786            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3787            0 :                 upload_index_part(
    3788            0 :                     &self.remote_storage,
    3789            0 :                     child_shard,
    3790            0 :                     &timeline_id,
    3791            0 :                     self.generation,
    3792            0 :                     &index_part,
    3793            0 :                     &self.cancel,
    3794            0 :                 )
    3795            0 :                 .await?;
    3796              :             }
    3797              :         }
    3798              : 
    3799            0 :         let tenant_manifest = self.build_tenant_manifest();
    3800            0 :         for child_shard in child_shards {
    3801            0 :             tracing::info!(
    3802            0 :                 "Uploading tenant manifest for child {}",
    3803            0 :                 child_shard.to_index()
    3804              :             );
    3805            0 :             upload_tenant_manifest(
    3806            0 :                 &self.remote_storage,
    3807            0 :                 child_shard,
    3808            0 :                 self.generation,
    3809            0 :                 &tenant_manifest,
    3810            0 :                 &self.cancel,
    3811            0 :             )
    3812            0 :             .await?;
    3813              :         }
    3814              : 
    3815            0 :         Ok(())
    3816            0 :     }
    3817              : 
    3818            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3819            0 :         let mut result = TopTenantShardItem {
    3820            0 :             id: self.tenant_shard_id,
    3821            0 :             resident_size: 0,
    3822            0 :             physical_size: 0,
    3823            0 :             max_logical_size: 0,
    3824            0 :         };
    3825              : 
    3826            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3827            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3828            0 : 
    3829            0 :             result.physical_size += timeline
    3830            0 :                 .remote_client
    3831            0 :                 .metrics
    3832            0 :                 .remote_physical_size_gauge
    3833            0 :                 .get();
    3834            0 :             result.max_logical_size = std::cmp::max(
    3835            0 :                 result.max_logical_size,
    3836            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3837            0 :             );
    3838            0 :         }
    3839              : 
    3840            0 :         result
    3841            0 :     }
    3842              : }
    3843              : 
    3844              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3845              : /// perform a topological sort, so that the parent of each timeline comes
    3846              : /// before the children.
    3847              : /// E extracts the ancestor from T
    3848              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3849          452 : fn tree_sort_timelines<T, E>(
    3850          452 :     timelines: HashMap<TimelineId, T>,
    3851          452 :     extractor: E,
    3852          452 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3853          452 : where
    3854          452 :     E: Fn(&T) -> Option<TimelineId>,
    3855          452 : {
    3856          452 :     let mut result = Vec::with_capacity(timelines.len());
    3857          452 : 
    3858          452 :     let mut now = Vec::with_capacity(timelines.len());
    3859          452 :     // (ancestor, children)
    3860          452 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3861          452 :         HashMap::with_capacity(timelines.len());
    3862              : 
    3863          464 :     for (timeline_id, value) in timelines {
    3864           12 :         if let Some(ancestor_id) = extractor(&value) {
    3865            4 :             let children = later.entry(ancestor_id).or_default();
    3866            4 :             children.push((timeline_id, value));
    3867            8 :         } else {
    3868            8 :             now.push((timeline_id, value));
    3869            8 :         }
    3870              :     }
    3871              : 
    3872          464 :     while let Some((timeline_id, metadata)) = now.pop() {
    3873           12 :         result.push((timeline_id, metadata));
    3874              :         // All children of this can be loaded now
    3875           12 :         if let Some(mut children) = later.remove(&timeline_id) {
    3876            4 :             now.append(&mut children);
    3877            8 :         }
    3878              :     }
    3879              : 
    3880              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3881          452 :     if !later.is_empty() {
    3882            0 :         for (missing_id, orphan_ids) in later {
    3883            0 :             for (orphan_id, _) in orphan_ids {
    3884            0 :                 error!(
    3885            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    3886              :                 );
    3887              :             }
    3888              :         }
    3889            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3890          452 :     }
    3891          452 : 
    3892          452 :     Ok(result)
    3893          452 : }
    3894              : 
    3895              : enum ActivateTimelineArgs {
    3896              :     Yes {
    3897              :         broker_client: storage_broker::BrokerClientChannel,
    3898              :     },
    3899              :     No,
    3900              : }
    3901              : 
    3902              : impl Tenant {
    3903            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3904            0 :         self.tenant_conf.load().tenant_conf.clone()
    3905            0 :     }
    3906              : 
    3907            0 :     pub fn effective_config(&self) -> TenantConf {
    3908            0 :         self.tenant_specific_overrides()
    3909            0 :             .merge(self.conf.default_tenant_conf.clone())
    3910            0 :     }
    3911              : 
    3912            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3913            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3914            0 :         tenant_conf
    3915            0 :             .checkpoint_distance
    3916            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3917            0 :     }
    3918              : 
    3919            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3920            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3921            0 :         tenant_conf
    3922            0 :             .checkpoint_timeout
    3923            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3924            0 :     }
    3925              : 
    3926            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3927            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3928            0 :         tenant_conf
    3929            0 :             .compaction_target_size
    3930            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3931            0 :     }
    3932              : 
    3933            0 :     pub fn get_compaction_period(&self) -> Duration {
    3934            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3935            0 :         tenant_conf
    3936            0 :             .compaction_period
    3937            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3938            0 :     }
    3939              : 
    3940            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3941            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3942            0 :         tenant_conf
    3943            0 :             .compaction_threshold
    3944            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3945            0 :     }
    3946              : 
    3947            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    3948            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3949            0 :         tenant_conf
    3950            0 :             .rel_size_v2_enabled
    3951            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    3952            0 :     }
    3953              : 
    3954            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    3955            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3956            0 :         tenant_conf
    3957            0 :             .compaction_upper_limit
    3958            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    3959            0 :     }
    3960              : 
    3961            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    3962            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3963            0 :         tenant_conf
    3964            0 :             .compaction_l0_first
    3965            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    3966            0 :     }
    3967              : 
    3968            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3969            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3970            0 :         tenant_conf
    3971            0 :             .gc_horizon
    3972            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3973            0 :     }
    3974              : 
    3975            0 :     pub fn get_gc_period(&self) -> Duration {
    3976            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3977            0 :         tenant_conf
    3978            0 :             .gc_period
    3979            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3980            0 :     }
    3981              : 
    3982            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3983            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3984            0 :         tenant_conf
    3985            0 :             .image_creation_threshold
    3986            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3987            0 :     }
    3988              : 
    3989            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3990            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3991            0 :         tenant_conf
    3992            0 :             .pitr_interval
    3993            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3994            0 :     }
    3995              : 
    3996            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3997            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3998            0 :         tenant_conf
    3999            0 :             .min_resident_size_override
    4000            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4001            0 :     }
    4002              : 
    4003            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4004            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4005            0 :         let heatmap_period = tenant_conf
    4006            0 :             .heatmap_period
    4007            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4008            0 :         if heatmap_period.is_zero() {
    4009            0 :             None
    4010              :         } else {
    4011            0 :             Some(heatmap_period)
    4012              :         }
    4013            0 :     }
    4014              : 
    4015            8 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4016            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4017            8 :         tenant_conf
    4018            8 :             .lsn_lease_length
    4019            8 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4020            8 :     }
    4021              : 
    4022            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4023            0 :         if self.conf.timeline_offloading {
    4024            0 :             return true;
    4025            0 :         }
    4026            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4027            0 :         tenant_conf
    4028            0 :             .timeline_offloading
    4029            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4030            0 :     }
    4031              : 
    4032              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4033            4 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4034            4 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    4035            4 : 
    4036            4 :         let mut timeline_manifests = timelines_offloaded
    4037            4 :             .iter()
    4038            4 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    4039            4 :             .collect::<Vec<_>>();
    4040            4 :         // Sort the manifests so that our output is deterministic
    4041            4 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    4042            4 : 
    4043            4 :         TenantManifest {
    4044            4 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4045            4 :             offloaded_timelines: timeline_manifests,
    4046            4 :         }
    4047            4 :     }
    4048              : 
    4049            0 :     pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
    4050            0 :         &self,
    4051            0 :         update: F,
    4052            0 :     ) -> anyhow::Result<TenantConfOpt> {
    4053            0 :         // Use read-copy-update in order to avoid overwriting the location config
    4054            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    4055            0 :         // this race is not possible if both request types come from the storage
    4056            0 :         // controller (as they should!) because an exclusive op lock is required
    4057            0 :         // on the storage controller side.
    4058            0 : 
    4059            0 :         self.tenant_conf
    4060            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4061            0 :                 Ok(Arc::new(AttachedTenantConf {
    4062            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4063            0 :                     location: attached_conf.location,
    4064            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4065              :                 }))
    4066            0 :             })?;
    4067              : 
    4068            0 :         let updated = self.tenant_conf.load();
    4069            0 : 
    4070            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    4071            0 :         // Don't hold self.timelines.lock() during the notifies.
    4072            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4073            0 :         // mutexes in struct Timeline in the future.
    4074            0 :         let timelines = self.list_timelines();
    4075            0 :         for timeline in timelines {
    4076            0 :             timeline.tenant_conf_updated(&updated);
    4077            0 :         }
    4078              : 
    4079            0 :         Ok(updated.tenant_conf.clone())
    4080            0 :     }
    4081              : 
    4082            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4083            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4084            0 : 
    4085            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4086            0 : 
    4087            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4088            0 :         // Don't hold self.timelines.lock() during the notifies.
    4089            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4090            0 :         // mutexes in struct Timeline in the future.
    4091            0 :         let timelines = self.list_timelines();
    4092            0 :         for timeline in timelines {
    4093            0 :             timeline.tenant_conf_updated(&new_conf);
    4094            0 :         }
    4095            0 :     }
    4096              : 
    4097          452 :     fn get_pagestream_throttle_config(
    4098          452 :         psconf: &'static PageServerConf,
    4099          452 :         overrides: &TenantConfOpt,
    4100          452 :     ) -> throttle::Config {
    4101          452 :         overrides
    4102          452 :             .timeline_get_throttle
    4103          452 :             .clone()
    4104          452 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4105          452 :     }
    4106              : 
    4107            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    4108            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4109            0 :         self.pagestream_throttle.reconfigure(conf)
    4110            0 :     }
    4111              : 
    4112              :     /// Helper function to create a new Timeline struct.
    4113              :     ///
    4114              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4115              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4116              :     /// map.
    4117              :     ///
    4118              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4119              :     /// and we might not have the ancestor present anymore which is fine for to be
    4120              :     /// deleted timelines.
    4121              :     #[allow(clippy::too_many_arguments)]
    4122          904 :     fn create_timeline_struct(
    4123          904 :         &self,
    4124          904 :         new_timeline_id: TimelineId,
    4125          904 :         new_metadata: &TimelineMetadata,
    4126          904 :         previous_heatmap: Option<PreviousHeatmap>,
    4127          904 :         ancestor: Option<Arc<Timeline>>,
    4128          904 :         resources: TimelineResources,
    4129          904 :         cause: CreateTimelineCause,
    4130          904 :         create_idempotency: CreateTimelineIdempotency,
    4131          904 :         gc_compaction_state: Option<GcCompactionState>,
    4132          904 :         rel_size_v2_status: Option<RelSizeMigration>,
    4133          904 :     ) -> anyhow::Result<Arc<Timeline>> {
    4134          904 :         let state = match cause {
    4135              :             CreateTimelineCause::Load => {
    4136          904 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4137          904 :                 anyhow::ensure!(
    4138          904 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4139            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4140              :                 );
    4141          904 :                 TimelineState::Loading
    4142              :             }
    4143            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4144              :         };
    4145              : 
    4146          904 :         let pg_version = new_metadata.pg_version();
    4147          904 : 
    4148          904 :         let timeline = Timeline::new(
    4149          904 :             self.conf,
    4150          904 :             Arc::clone(&self.tenant_conf),
    4151          904 :             new_metadata,
    4152          904 :             previous_heatmap,
    4153          904 :             ancestor,
    4154          904 :             new_timeline_id,
    4155          904 :             self.tenant_shard_id,
    4156          904 :             self.generation,
    4157          904 :             self.shard_identity,
    4158          904 :             self.walredo_mgr.clone(),
    4159          904 :             resources,
    4160          904 :             pg_version,
    4161          904 :             state,
    4162          904 :             self.attach_wal_lag_cooldown.clone(),
    4163          904 :             create_idempotency,
    4164          904 :             gc_compaction_state,
    4165          904 :             rel_size_v2_status,
    4166          904 :             self.cancel.child_token(),
    4167          904 :         );
    4168          904 : 
    4169          904 :         Ok(timeline)
    4170          904 :     }
    4171              : 
    4172              :     /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
    4173              :     /// to ensure proper cleanup of background tasks and metrics.
    4174              :     //
    4175              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4176              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4177              :     #[allow(clippy::too_many_arguments)]
    4178          452 :     fn new(
    4179          452 :         state: TenantState,
    4180          452 :         conf: &'static PageServerConf,
    4181          452 :         attached_conf: AttachedTenantConf,
    4182          452 :         shard_identity: ShardIdentity,
    4183          452 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4184          452 :         tenant_shard_id: TenantShardId,
    4185          452 :         remote_storage: GenericRemoteStorage,
    4186          452 :         deletion_queue_client: DeletionQueueClient,
    4187          452 :         l0_flush_global_state: L0FlushGlobalState,
    4188          452 :     ) -> Tenant {
    4189          452 :         debug_assert!(
    4190          452 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4191              :         );
    4192              : 
    4193          452 :         let (state, mut rx) = watch::channel(state);
    4194          452 : 
    4195          452 :         tokio::spawn(async move {
    4196          452 :             // reflect tenant state in metrics:
    4197          452 :             // - global per tenant state: TENANT_STATE_METRIC
    4198          452 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4199          452 :             //
    4200          452 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4201          452 :             // alerting.
    4202          452 : 
    4203          452 :             let tid = tenant_shard_id.to_string();
    4204          452 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4205          452 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4206              : 
    4207          904 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4208          904 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4209          904 :             }
    4210              : 
    4211          452 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4212          452 : 
    4213          452 :             let is_broken = tuple.1;
    4214          452 :             let mut counted_broken = if is_broken {
    4215              :                 // add the id to the set right away, there should not be any updates on the channel
    4216              :                 // after before tenant is removed, if ever
    4217            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4218            0 :                 true
    4219              :             } else {
    4220          452 :                 false
    4221              :             };
    4222              : 
    4223              :             loop {
    4224          904 :                 let labels = &tuple.0;
    4225          904 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4226          904 :                 current.inc();
    4227          904 : 
    4228          904 :                 if rx.changed().await.is_err() {
    4229              :                     // tenant has been dropped
    4230           28 :                     current.dec();
    4231           28 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4232           28 :                     break;
    4233          452 :                 }
    4234          452 : 
    4235          452 :                 current.dec();
    4236          452 :                 tuple = inspect_state(&rx.borrow_and_update());
    4237          452 : 
    4238          452 :                 let is_broken = tuple.1;
    4239          452 :                 if is_broken && !counted_broken {
    4240            0 :                     counted_broken = true;
    4241            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4242            0 :                     // access
    4243            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4244          452 :                 }
    4245              :             }
    4246          452 :         });
    4247          452 : 
    4248          452 :         Tenant {
    4249          452 :             tenant_shard_id,
    4250          452 :             shard_identity,
    4251          452 :             generation: attached_conf.location.generation,
    4252          452 :             conf,
    4253          452 :             // using now here is good enough approximation to catch tenants with really long
    4254          452 :             // activation times.
    4255          452 :             constructed_at: Instant::now(),
    4256          452 :             timelines: Mutex::new(HashMap::new()),
    4257          452 :             timelines_creating: Mutex::new(HashSet::new()),
    4258          452 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4259          452 :             tenant_manifest_upload: Default::default(),
    4260          452 :             gc_cs: tokio::sync::Mutex::new(()),
    4261          452 :             walredo_mgr,
    4262          452 :             remote_storage,
    4263          452 :             deletion_queue_client,
    4264          452 :             state,
    4265          452 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4266          452 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4267          452 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4268          452 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4269          452 :                 format!("compaction-{tenant_shard_id}"),
    4270          452 :                 5,
    4271          452 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4272          452 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4273          452 :                 // use an extremely long backoff.
    4274          452 :                 Some(Duration::from_secs(3600 * 24)),
    4275          452 :             )),
    4276          452 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4277          452 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4278          452 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4279          452 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4280          452 :             cancel: CancellationToken::default(),
    4281          452 :             gate: Gate::default(),
    4282          452 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4283          452 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4284          452 :             )),
    4285          452 :             pagestream_throttle_metrics: Arc::new(
    4286          452 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4287          452 :             ),
    4288          452 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4289          452 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4290          452 :             gc_block: Default::default(),
    4291          452 :             l0_flush_global_state,
    4292          452 :         }
    4293          452 :     }
    4294              : 
    4295              :     /// Locate and load config
    4296            0 :     pub(super) fn load_tenant_config(
    4297            0 :         conf: &'static PageServerConf,
    4298            0 :         tenant_shard_id: &TenantShardId,
    4299            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4300            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4301            0 : 
    4302            0 :         info!("loading tenant configuration from {config_path}");
    4303              : 
    4304              :         // load and parse file
    4305            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4306            0 :             match e.kind() {
    4307              :                 std::io::ErrorKind::NotFound => {
    4308              :                     // The config should almost always exist for a tenant directory:
    4309              :                     //  - When attaching a tenant, the config is the first thing we write
    4310              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4311              :                     //    before deleting contents.
    4312              :                     //
    4313              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4314              :                     // between creating directory and writing config.  Callers should handle that as if the
    4315              :                     // directory didn't exist.
    4316              : 
    4317            0 :                     LoadConfigError::NotFound(config_path)
    4318              :                 }
    4319              :                 _ => {
    4320              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4321              :                     // that we cannot cleanly recover
    4322            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4323              :                 }
    4324              :             }
    4325            0 :         })?;
    4326              : 
    4327            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4328            0 :     }
    4329              : 
    4330              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4331              :     pub(super) async fn persist_tenant_config(
    4332              :         conf: &'static PageServerConf,
    4333              :         tenant_shard_id: &TenantShardId,
    4334              :         location_conf: &LocationConf,
    4335              :     ) -> std::io::Result<()> {
    4336              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4337              : 
    4338              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4339              :     }
    4340              : 
    4341              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4342              :     pub(super) async fn persist_tenant_config_at(
    4343              :         tenant_shard_id: &TenantShardId,
    4344              :         config_path: &Utf8Path,
    4345              :         location_conf: &LocationConf,
    4346              :     ) -> std::io::Result<()> {
    4347              :         debug!("persisting tenantconf to {config_path}");
    4348              : 
    4349              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4350              : #  It is read in case of pageserver restart.
    4351              : "#
    4352              :         .to_string();
    4353              : 
    4354            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4355            0 :             Err(std::io::Error::new(
    4356            0 :                 std::io::ErrorKind::Other,
    4357            0 :                 "tenant-config-before-write",
    4358            0 :             ))
    4359            0 :         });
    4360              : 
    4361              :         // Convert the config to a toml file.
    4362              :         conf_content +=
    4363              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4364              : 
    4365              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4366              : 
    4367              :         let conf_content = conf_content.into_bytes();
    4368              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4369              :     }
    4370              : 
    4371              :     //
    4372              :     // How garbage collection works:
    4373              :     //
    4374              :     //                    +--bar------------->
    4375              :     //                   /
    4376              :     //             +----+-----foo---------------->
    4377              :     //            /
    4378              :     // ----main--+-------------------------->
    4379              :     //                \
    4380              :     //                 +-----baz-------->
    4381              :     //
    4382              :     //
    4383              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4384              :     //    `gc_infos` are being refreshed
    4385              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4386              :     //    all the points where other timelines have been branched off.
    4387              :     //    We will refrain from removing page versions at those LSNs.
    4388              :     // 3. For each timeline, scan all layer files on the timeline.
    4389              :     //    Remove all files for which a newer file exists and which
    4390              :     //    don't cover any branch point LSNs.
    4391              :     //
    4392              :     // TODO:
    4393              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4394              :     //   don't need to keep that in the parent anymore. But currently
    4395              :     //   we do.
    4396            8 :     async fn gc_iteration_internal(
    4397            8 :         &self,
    4398            8 :         target_timeline_id: Option<TimelineId>,
    4399            8 :         horizon: u64,
    4400            8 :         pitr: Duration,
    4401            8 :         cancel: &CancellationToken,
    4402            8 :         ctx: &RequestContext,
    4403            8 :     ) -> Result<GcResult, GcError> {
    4404            8 :         let mut totals: GcResult = Default::default();
    4405            8 :         let now = Instant::now();
    4406              : 
    4407            8 :         let gc_timelines = self
    4408            8 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4409            8 :             .await?;
    4410              : 
    4411            8 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4412              : 
    4413              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4414            8 :         if !gc_timelines.is_empty() {
    4415            8 :             info!("{} timelines need GC", gc_timelines.len());
    4416              :         } else {
    4417            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4418              :         }
    4419              : 
    4420              :         // Perform GC for each timeline.
    4421              :         //
    4422              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4423              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4424              :         // with branch creation.
    4425              :         //
    4426              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4427              :         // creation task can run concurrently with timeline's GC iteration.
    4428           16 :         for timeline in gc_timelines {
    4429            8 :             if cancel.is_cancelled() {
    4430              :                 // We were requested to shut down. Stop and return with the progress we
    4431              :                 // made.
    4432            0 :                 break;
    4433            8 :             }
    4434            8 :             let result = match timeline.gc().await {
    4435              :                 Err(GcError::TimelineCancelled) => {
    4436            0 :                     if target_timeline_id.is_some() {
    4437              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4438            0 :                         return Err(GcError::TimelineCancelled);
    4439              :                     } else {
    4440              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4441              :                         // skip past this and proceed to try GC on other timelines.
    4442            0 :                         continue;
    4443              :                     }
    4444              :                 }
    4445            8 :                 r => r?,
    4446              :             };
    4447            8 :             totals += result;
    4448              :         }
    4449              : 
    4450            8 :         totals.elapsed = now.elapsed();
    4451            8 :         Ok(totals)
    4452            8 :     }
    4453              : 
    4454              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4455              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4456              :     /// [`Tenant::get_gc_horizon`].
    4457              :     ///
    4458              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4459            0 :     pub(crate) async fn refresh_gc_info(
    4460            0 :         &self,
    4461            0 :         cancel: &CancellationToken,
    4462            0 :         ctx: &RequestContext,
    4463            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4464            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4465            0 :         // might be that these configuration values get applied faster than what it was previously,
    4466            0 :         // since these were only read from the gc task.
    4467            0 :         let horizon = self.get_gc_horizon();
    4468            0 :         let pitr = self.get_pitr_interval();
    4469            0 : 
    4470            0 :         // refresh all timelines
    4471            0 :         let target_timeline_id = None;
    4472            0 : 
    4473            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4474            0 :             .await
    4475            0 :     }
    4476              : 
    4477              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4478              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4479              :     ///
    4480              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4481            0 :     fn initialize_gc_info(
    4482            0 :         &self,
    4483            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4484            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4485            0 :         restrict_to_timeline: Option<TimelineId>,
    4486            0 :     ) {
    4487            0 :         if restrict_to_timeline.is_none() {
    4488              :             // This function must be called before activation: after activation timeline create/delete operations
    4489              :             // might happen, and this function is not safe to run concurrently with those.
    4490            0 :             assert!(!self.is_active());
    4491            0 :         }
    4492              : 
    4493              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4494              :         // the branch point where it was created.
    4495            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4496            0 :             BTreeMap::new();
    4497            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4498            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4499            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4500            0 :                 ancestor_children.push((
    4501            0 :                     timeline_entry.get_ancestor_lsn(),
    4502            0 :                     *timeline_id,
    4503            0 :                     MaybeOffloaded::No,
    4504            0 :                 ));
    4505            0 :             }
    4506            0 :         });
    4507            0 :         timelines_offloaded
    4508            0 :             .iter()
    4509            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4510            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4511            0 :                     return;
    4512              :                 };
    4513            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4514            0 :                     return;
    4515              :                 };
    4516            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4517            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4518            0 :             });
    4519            0 : 
    4520            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4521            0 :         let horizon = self.get_gc_horizon();
    4522              : 
    4523              :         // Populate each timeline's GcInfo with information about its child branches
    4524            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4525            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4526              :         } else {
    4527            0 :             itertools::Either::Right(timelines.values())
    4528              :         };
    4529            0 :         for timeline in timelines_to_write {
    4530            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4531            0 :                 .remove(&timeline.timeline_id)
    4532            0 :                 .unwrap_or_default();
    4533            0 : 
    4534            0 :             branchpoints.sort_by_key(|b| b.0);
    4535            0 : 
    4536            0 :             let mut target = timeline.gc_info.write().unwrap();
    4537            0 : 
    4538            0 :             target.retain_lsns = branchpoints;
    4539            0 : 
    4540            0 :             let space_cutoff = timeline
    4541            0 :                 .get_last_record_lsn()
    4542            0 :                 .checked_sub(horizon)
    4543            0 :                 .unwrap_or(Lsn(0));
    4544            0 : 
    4545            0 :             target.cutoffs = GcCutoffs {
    4546            0 :                 space: space_cutoff,
    4547            0 :                 time: Lsn::INVALID,
    4548            0 :             };
    4549            0 :         }
    4550            0 :     }
    4551              : 
    4552            8 :     async fn refresh_gc_info_internal(
    4553            8 :         &self,
    4554            8 :         target_timeline_id: Option<TimelineId>,
    4555            8 :         horizon: u64,
    4556            8 :         pitr: Duration,
    4557            8 :         cancel: &CancellationToken,
    4558            8 :         ctx: &RequestContext,
    4559            8 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4560            8 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4561            8 :         // currently visible timelines.
    4562            8 :         let timelines = self
    4563            8 :             .timelines
    4564            8 :             .lock()
    4565            8 :             .unwrap()
    4566            8 :             .values()
    4567            8 :             .filter(|tl| match target_timeline_id.as_ref() {
    4568            8 :                 Some(target) => &tl.timeline_id == target,
    4569            0 :                 None => true,
    4570            8 :             })
    4571            8 :             .cloned()
    4572            8 :             .collect::<Vec<_>>();
    4573            8 : 
    4574            8 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4575              :             // We were to act on a particular timeline and it wasn't found
    4576            0 :             return Err(GcError::TimelineNotFound);
    4577            8 :         }
    4578            8 : 
    4579            8 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4580            8 :             HashMap::with_capacity(timelines.len());
    4581            8 : 
    4582            8 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4583            8 :         let now_ts_for_pitr_calc = SystemTime::now();
    4584            8 :         for timeline in timelines.iter() {
    4585            8 :             let cutoff = timeline
    4586            8 :                 .get_last_record_lsn()
    4587            8 :                 .checked_sub(horizon)
    4588            8 :                 .unwrap_or(Lsn(0));
    4589              : 
    4590            8 :             let cutoffs = timeline
    4591            8 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4592            8 :                 .await?;
    4593            8 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4594            8 :             assert!(old.is_none());
    4595              :         }
    4596              : 
    4597            8 :         if !self.is_active() || self.cancel.is_cancelled() {
    4598            0 :             return Err(GcError::TenantCancelled);
    4599            8 :         }
    4600              : 
    4601              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4602              :         // because that will stall branch creation.
    4603            8 :         let gc_cs = self.gc_cs.lock().await;
    4604              : 
    4605              :         // Ok, we now know all the branch points.
    4606              :         // Update the GC information for each timeline.
    4607            8 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4608           16 :         for timeline in timelines {
    4609              :             // We filtered the timeline list above
    4610            8 :             if let Some(target_timeline_id) = target_timeline_id {
    4611            8 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4612            0 :             }
    4613              : 
    4614              :             {
    4615            8 :                 let mut target = timeline.gc_info.write().unwrap();
    4616            8 : 
    4617            8 :                 // Cull any expired leases
    4618            8 :                 let now = SystemTime::now();
    4619           12 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4620            8 : 
    4621            8 :                 timeline
    4622            8 :                     .metrics
    4623            8 :                     .valid_lsn_lease_count_gauge
    4624            8 :                     .set(target.leases.len() as u64);
    4625              : 
    4626              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4627            8 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4628            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4629            0 :                         target.within_ancestor_pitr =
    4630            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4631            0 :                     }
    4632            8 :                 }
    4633              : 
    4634              :                 // Update metrics that depend on GC state
    4635            8 :                 timeline
    4636            8 :                     .metrics
    4637            8 :                     .archival_size
    4638            8 :                     .set(if target.within_ancestor_pitr {
    4639            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4640              :                     } else {
    4641            8 :                         0
    4642              :                     });
    4643            8 :                 timeline.metrics.pitr_history_size.set(
    4644            8 :                     timeline
    4645            8 :                         .get_last_record_lsn()
    4646            8 :                         .checked_sub(target.cutoffs.time)
    4647            8 :                         .unwrap_or(Lsn(0))
    4648            8 :                         .0,
    4649            8 :                 );
    4650              : 
    4651              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4652              :                 // - this timeline was created while we were finding cutoffs
    4653              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4654            8 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4655            8 :                     let original_cutoffs = target.cutoffs.clone();
    4656            8 :                     // GC cutoffs should never go back
    4657            8 :                     target.cutoffs = GcCutoffs {
    4658            8 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4659            8 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4660            8 :                     }
    4661            0 :                 }
    4662              :             }
    4663              : 
    4664            8 :             gc_timelines.push(timeline);
    4665              :         }
    4666            8 :         drop(gc_cs);
    4667            8 :         Ok(gc_timelines)
    4668            8 :     }
    4669              : 
    4670              :     /// A substitute for `branch_timeline` for use in unit tests.
    4671              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4672              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4673              :     /// timeline background tasks are launched, except the flush loop.
    4674              :     #[cfg(test)]
    4675          464 :     async fn branch_timeline_test(
    4676          464 :         self: &Arc<Self>,
    4677          464 :         src_timeline: &Arc<Timeline>,
    4678          464 :         dst_id: TimelineId,
    4679          464 :         ancestor_lsn: Option<Lsn>,
    4680          464 :         ctx: &RequestContext,
    4681          464 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4682          464 :         let tl = self
    4683          464 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4684          464 :             .await?
    4685          456 :             .into_timeline_for_test();
    4686          456 :         tl.set_state(TimelineState::Active);
    4687          456 :         Ok(tl)
    4688          464 :     }
    4689              : 
    4690              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4691              :     #[cfg(test)]
    4692              :     #[allow(clippy::too_many_arguments)]
    4693           12 :     pub async fn branch_timeline_test_with_layers(
    4694           12 :         self: &Arc<Self>,
    4695           12 :         src_timeline: &Arc<Timeline>,
    4696           12 :         dst_id: TimelineId,
    4697           12 :         ancestor_lsn: Option<Lsn>,
    4698           12 :         ctx: &RequestContext,
    4699           12 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4700           12 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4701           12 :         end_lsn: Lsn,
    4702           12 :     ) -> anyhow::Result<Arc<Timeline>> {
    4703              :         use checks::check_valid_layermap;
    4704              :         use itertools::Itertools;
    4705              : 
    4706           12 :         let tline = self
    4707           12 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4708           12 :             .await?;
    4709           12 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4710           12 :             ancestor_lsn
    4711              :         } else {
    4712            0 :             tline.get_last_record_lsn()
    4713              :         };
    4714           12 :         assert!(end_lsn >= ancestor_lsn);
    4715           12 :         tline.force_advance_lsn(end_lsn);
    4716           24 :         for deltas in delta_layer_desc {
    4717           12 :             tline
    4718           12 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4719           12 :                 .await?;
    4720              :         }
    4721           20 :         for (lsn, images) in image_layer_desc {
    4722            8 :             tline
    4723            8 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4724            8 :                 .await?;
    4725              :         }
    4726           12 :         let layer_names = tline
    4727           12 :             .layers
    4728           12 :             .read()
    4729           12 :             .await
    4730           12 :             .layer_map()
    4731           12 :             .unwrap()
    4732           12 :             .iter_historic_layers()
    4733           20 :             .map(|layer| layer.layer_name())
    4734           12 :             .collect_vec();
    4735           12 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4736            0 :             bail!("invalid layermap: {err}");
    4737           12 :         }
    4738           12 :         Ok(tline)
    4739           12 :     }
    4740              : 
    4741              :     /// Branch an existing timeline.
    4742            0 :     async fn branch_timeline(
    4743            0 :         self: &Arc<Self>,
    4744            0 :         src_timeline: &Arc<Timeline>,
    4745            0 :         dst_id: TimelineId,
    4746            0 :         start_lsn: Option<Lsn>,
    4747            0 :         ctx: &RequestContext,
    4748            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4749            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4750            0 :             .await
    4751            0 :     }
    4752              : 
    4753          464 :     async fn branch_timeline_impl(
    4754          464 :         self: &Arc<Self>,
    4755          464 :         src_timeline: &Arc<Timeline>,
    4756          464 :         dst_id: TimelineId,
    4757          464 :         start_lsn: Option<Lsn>,
    4758          464 :         _ctx: &RequestContext,
    4759          464 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4760          464 :         let src_id = src_timeline.timeline_id;
    4761              : 
    4762              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4763              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4764              :         // valid while we are creating the branch.
    4765          464 :         let _gc_cs = self.gc_cs.lock().await;
    4766              : 
    4767              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4768          464 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4769            4 :             let lsn = src_timeline.get_last_record_lsn();
    4770            4 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4771            4 :             lsn
    4772          464 :         });
    4773              : 
    4774              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4775          464 :         let timeline_create_guard = match self
    4776          464 :             .start_creating_timeline(
    4777          464 :                 dst_id,
    4778          464 :                 CreateTimelineIdempotency::Branch {
    4779          464 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4780          464 :                     ancestor_start_lsn: start_lsn,
    4781          464 :                 },
    4782          464 :             )
    4783          464 :             .await?
    4784              :         {
    4785          464 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4786            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4787            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4788              :             }
    4789              :         };
    4790              : 
    4791              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4792              :         // horizon on the source timeline
    4793              :         //
    4794              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4795              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4796              :         // planned GC cutoff in 'gc_info' is normally larger than
    4797              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    4798              :         // changed the GC settings for the tenant to make the PITR window
    4799              :         // larger, but some of the data was already removed by an earlier GC
    4800              :         // iteration.
    4801              : 
    4802              :         // check against last actual 'latest_gc_cutoff' first
    4803          464 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    4804          464 :         {
    4805          464 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4806          464 :             let planned_cutoff = gc_info.min_cutoff();
    4807          464 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    4808            0 :                 tracing::info!(
    4809            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    4810            0 :                     *applied_gc_cutoff_lsn
    4811              :                 );
    4812              :             } else {
    4813          464 :                 src_timeline
    4814          464 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    4815          464 :                     .context(format!(
    4816          464 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    4817          464 :                         *applied_gc_cutoff_lsn,
    4818          464 :                     ))
    4819          464 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    4820              : 
    4821              :                 // and then the planned GC cutoff
    4822          456 :                 if start_lsn < planned_cutoff {
    4823            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4824            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    4825            0 :                     )));
    4826          456 :                 }
    4827              :             }
    4828              :         }
    4829              : 
    4830              :         //
    4831              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4832              :         // so that GC cannot advance the GC cutoff until we are finished.
    4833              :         // Proceed with the branch creation.
    4834              :         //
    4835              : 
    4836              :         // Determine prev-LSN for the new timeline. We can only determine it if
    4837              :         // the timeline was branched at the current end of the source timeline.
    4838              :         let RecordLsn {
    4839          456 :             last: src_last,
    4840          456 :             prev: src_prev,
    4841          456 :         } = src_timeline.get_last_record_rlsn();
    4842          456 :         let dst_prev = if src_last == start_lsn {
    4843          432 :             Some(src_prev)
    4844              :         } else {
    4845           24 :             None
    4846              :         };
    4847              : 
    4848              :         // Create the metadata file, noting the ancestor of the new timeline.
    4849              :         // There is initially no data in it, but all the read-calls know to look
    4850              :         // into the ancestor.
    4851          456 :         let metadata = TimelineMetadata::new(
    4852          456 :             start_lsn,
    4853          456 :             dst_prev,
    4854          456 :             Some(src_id),
    4855          456 :             start_lsn,
    4856          456 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4857          456 :             src_timeline.initdb_lsn,
    4858          456 :             src_timeline.pg_version,
    4859          456 :         );
    4860              : 
    4861          456 :         let uninitialized_timeline = self
    4862          456 :             .prepare_new_timeline(
    4863          456 :                 dst_id,
    4864          456 :                 &metadata,
    4865          456 :                 timeline_create_guard,
    4866          456 :                 start_lsn + 1,
    4867          456 :                 Some(Arc::clone(src_timeline)),
    4868          456 :             )
    4869          456 :             .await?;
    4870              : 
    4871          456 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    4872              : 
    4873              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4874              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4875              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4876              :         // could get incorrect information and remove more layers, than needed.
    4877              :         // See also https://github.com/neondatabase/neon/issues/3865
    4878          456 :         new_timeline
    4879          456 :             .remote_client
    4880          456 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4881          456 :             .context("branch initial metadata upload")?;
    4882              : 
    4883              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4884              : 
    4885          456 :         Ok(CreateTimelineResult::Created(new_timeline))
    4886          464 :     }
    4887              : 
    4888              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4889              :     #[cfg(test)]
    4890              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4891              :     pub(crate) async fn bootstrap_timeline_test(
    4892              :         self: &Arc<Self>,
    4893              :         timeline_id: TimelineId,
    4894              :         pg_version: u32,
    4895              :         load_existing_initdb: Option<TimelineId>,
    4896              :         ctx: &RequestContext,
    4897              :     ) -> anyhow::Result<Arc<Timeline>> {
    4898              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4899              :             .await
    4900              :             .map_err(anyhow::Error::new)
    4901            4 :             .map(|r| r.into_timeline_for_test())
    4902              :     }
    4903              : 
    4904              :     /// Get exclusive access to the timeline ID for creation.
    4905              :     ///
    4906              :     /// Timeline-creating code paths must use this function before making changes
    4907              :     /// to in-memory or persistent state.
    4908              :     ///
    4909              :     /// The `state` parameter is a description of the timeline creation operation
    4910              :     /// we intend to perform.
    4911              :     /// If the timeline was already created in the meantime, we check whether this
    4912              :     /// request conflicts or is idempotent , based on `state`.
    4913          904 :     async fn start_creating_timeline(
    4914          904 :         self: &Arc<Self>,
    4915          904 :         new_timeline_id: TimelineId,
    4916          904 :         idempotency: CreateTimelineIdempotency,
    4917          904 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4918          904 :         let allow_offloaded = false;
    4919          904 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4920          900 :             Ok(create_guard) => {
    4921          900 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4922          900 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4923              :             }
    4924            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4925              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4926              :                 // Creation is in progress, we cannot create it again, and we cannot
    4927              :                 // check if this request matches the existing one, so caller must try
    4928              :                 // again later.
    4929            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4930              :             }
    4931            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4932              :             Err(TimelineExclusionError::AlreadyExists {
    4933            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4934            0 :                 ..
    4935            0 :             }) => {
    4936            0 :                 info!("timeline already exists but is offloaded");
    4937            0 :                 Err(CreateTimelineError::Conflict)
    4938              :             }
    4939              :             Err(TimelineExclusionError::AlreadyExists {
    4940            4 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4941            4 :                 arg,
    4942            4 :             }) => {
    4943            4 :                 {
    4944            4 :                     let existing = &existing.create_idempotency;
    4945            4 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4946            4 :                     debug!("timeline already exists");
    4947              : 
    4948            4 :                     match (existing, &arg) {
    4949              :                         // FailWithConflict => no idempotency check
    4950              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4951              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4952            4 :                             warn!("timeline already exists, failing request");
    4953            4 :                             return Err(CreateTimelineError::Conflict);
    4954              :                         }
    4955              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4956            0 :                         (x, y) if x == y => {
    4957            0 :                             info!(
    4958            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    4959              :                             );
    4960              :                             // fallthrough
    4961              :                         }
    4962              :                         (_, _) => {
    4963            0 :                             warn!("idempotency conflict, failing request");
    4964            0 :                             return Err(CreateTimelineError::Conflict);
    4965              :                         }
    4966              :                     }
    4967              :                 }
    4968              : 
    4969            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4970              :             }
    4971              :         }
    4972          904 :     }
    4973              : 
    4974            0 :     async fn upload_initdb(
    4975            0 :         &self,
    4976            0 :         timelines_path: &Utf8PathBuf,
    4977            0 :         pgdata_path: &Utf8PathBuf,
    4978            0 :         timeline_id: &TimelineId,
    4979            0 :     ) -> anyhow::Result<()> {
    4980            0 :         let temp_path = timelines_path.join(format!(
    4981            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4982            0 :         ));
    4983            0 : 
    4984            0 :         scopeguard::defer! {
    4985            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4986            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4987            0 :             }
    4988            0 :         }
    4989              : 
    4990            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4991              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4992            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4993            0 :             warn!(
    4994            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4995              :             );
    4996            0 :         }
    4997              : 
    4998            0 :         pausable_failpoint!("before-initdb-upload");
    4999              : 
    5000            0 :         backoff::retry(
    5001            0 :             || async {
    5002            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5003            0 :                     &self.remote_storage,
    5004            0 :                     &self.tenant_shard_id.tenant_id,
    5005            0 :                     timeline_id,
    5006            0 :                     pgdata_zstd.try_clone().await?,
    5007            0 :                     tar_zst_size,
    5008            0 :                     &self.cancel,
    5009            0 :                 )
    5010            0 :                 .await
    5011            0 :             },
    5012            0 :             |_| false,
    5013            0 :             3,
    5014            0 :             u32::MAX,
    5015            0 :             "persist_initdb_tar_zst",
    5016            0 :             &self.cancel,
    5017            0 :         )
    5018            0 :         .await
    5019            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5020            0 :         .and_then(|x| x)
    5021            0 :     }
    5022              : 
    5023              :     /// - run initdb to init temporary instance and get bootstrap data
    5024              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5025            4 :     async fn bootstrap_timeline(
    5026            4 :         self: &Arc<Self>,
    5027            4 :         timeline_id: TimelineId,
    5028            4 :         pg_version: u32,
    5029            4 :         load_existing_initdb: Option<TimelineId>,
    5030            4 :         ctx: &RequestContext,
    5031            4 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5032            4 :         let timeline_create_guard = match self
    5033            4 :             .start_creating_timeline(
    5034            4 :                 timeline_id,
    5035            4 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5036            4 :             )
    5037            4 :             .await?
    5038              :         {
    5039            4 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5040            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5041            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5042              :             }
    5043              :         };
    5044              : 
    5045              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5046              :         // temporary directory for basebackup files for the given timeline.
    5047              : 
    5048            4 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5049            4 :         let pgdata_path = path_with_suffix_extension(
    5050            4 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5051            4 :             TEMP_FILE_SUFFIX,
    5052            4 :         );
    5053            4 : 
    5054            4 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5055            4 :         // we won't race with other creations or existent timelines with the same path.
    5056            4 :         if pgdata_path.exists() {
    5057            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5058            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5059            0 :             })?;
    5060            4 :         }
    5061              : 
    5062              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5063            4 :         let pgdata_path_deferred = pgdata_path.clone();
    5064            4 :         scopeguard::defer! {
    5065            4 :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred) {
    5066            4 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5067            4 :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5068            4 :             }
    5069            4 :         }
    5070            4 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5071            4 :             if existing_initdb_timeline_id != timeline_id {
    5072            0 :                 let source_path = &remote_initdb_archive_path(
    5073            0 :                     &self.tenant_shard_id.tenant_id,
    5074            0 :                     &existing_initdb_timeline_id,
    5075            0 :                 );
    5076            0 :                 let dest_path =
    5077            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5078            0 : 
    5079            0 :                 // if this fails, it will get retried by retried control plane requests
    5080            0 :                 self.remote_storage
    5081            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5082            0 :                     .await
    5083            0 :                     .context("copy initdb tar")?;
    5084            4 :             }
    5085            4 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5086            4 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5087            4 :                     self.conf,
    5088            4 :                     &self.remote_storage,
    5089            4 :                     &self.tenant_shard_id,
    5090            4 :                     &existing_initdb_timeline_id,
    5091            4 :                     &self.cancel,
    5092            4 :                 )
    5093            4 :                 .await
    5094            4 :                 .context("download initdb tar")?;
    5095              : 
    5096            4 :             scopeguard::defer! {
    5097            4 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5098            4 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5099            4 :                 }
    5100            4 :             }
    5101            4 : 
    5102            4 :             let buf_read =
    5103            4 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5104            4 :             extract_zst_tarball(&pgdata_path, buf_read)
    5105            4 :                 .await
    5106            4 :                 .context("extract initdb tar")?;
    5107              :         } else {
    5108              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5109            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5110            0 :                 .await
    5111            0 :                 .context("run initdb")?;
    5112              : 
    5113              :             // Upload the created data dir to S3
    5114            0 :             if self.tenant_shard_id().is_shard_zero() {
    5115            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5116            0 :                     .await?;
    5117            0 :             }
    5118              :         }
    5119            4 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5120            4 : 
    5121            4 :         // Import the contents of the data directory at the initial checkpoint
    5122            4 :         // LSN, and any WAL after that.
    5123            4 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5124            4 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5125            4 :         let new_metadata = TimelineMetadata::new(
    5126            4 :             Lsn(0),
    5127            4 :             None,
    5128            4 :             None,
    5129            4 :             Lsn(0),
    5130            4 :             pgdata_lsn,
    5131            4 :             pgdata_lsn,
    5132            4 :             pg_version,
    5133            4 :         );
    5134            4 :         let mut raw_timeline = self
    5135            4 :             .prepare_new_timeline(
    5136            4 :                 timeline_id,
    5137            4 :                 &new_metadata,
    5138            4 :                 timeline_create_guard,
    5139            4 :                 pgdata_lsn,
    5140            4 :                 None,
    5141            4 :             )
    5142            4 :             .await?;
    5143              : 
    5144            4 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5145            4 :         raw_timeline
    5146            4 :             .write(|unfinished_timeline| async move {
    5147            4 :                 import_datadir::import_timeline_from_postgres_datadir(
    5148            4 :                     &unfinished_timeline,
    5149            4 :                     &pgdata_path,
    5150            4 :                     pgdata_lsn,
    5151            4 :                     ctx,
    5152            4 :                 )
    5153            4 :                 .await
    5154            4 :                 .with_context(|| {
    5155            0 :                     format!(
    5156            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5157            0 :                     )
    5158            4 :                 })?;
    5159              : 
    5160            4 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5161            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5162            0 :                         "failpoint before-checkpoint-new-timeline"
    5163            0 :                     )))
    5164            4 :                 });
    5165              : 
    5166            4 :                 Ok(())
    5167            8 :             })
    5168            4 :             .await?;
    5169              : 
    5170              :         // All done!
    5171            4 :         let timeline = raw_timeline.finish_creation().await?;
    5172              : 
    5173              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5174              : 
    5175            4 :         Ok(CreateTimelineResult::Created(timeline))
    5176            4 :     }
    5177              : 
    5178          892 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5179          892 :         RemoteTimelineClient::new(
    5180          892 :             self.remote_storage.clone(),
    5181          892 :             self.deletion_queue_client.clone(),
    5182          892 :             self.conf,
    5183          892 :             self.tenant_shard_id,
    5184          892 :             timeline_id,
    5185          892 :             self.generation,
    5186          892 :             &self.tenant_conf.load().location,
    5187          892 :         )
    5188          892 :     }
    5189              : 
    5190              :     /// Builds required resources for a new timeline.
    5191          892 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5192          892 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5193          892 :         self.get_timeline_resources_for(remote_client)
    5194          892 :     }
    5195              : 
    5196              :     /// Builds timeline resources for the given remote client.
    5197          904 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5198          904 :         TimelineResources {
    5199          904 :             remote_client,
    5200          904 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5201          904 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5202          904 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5203          904 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5204          904 :         }
    5205          904 :     }
    5206              : 
    5207              :     /// Creates intermediate timeline structure and its files.
    5208              :     ///
    5209              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5210              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5211              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5212          892 :     async fn prepare_new_timeline<'a>(
    5213          892 :         &'a self,
    5214          892 :         new_timeline_id: TimelineId,
    5215          892 :         new_metadata: &TimelineMetadata,
    5216          892 :         create_guard: TimelineCreateGuard,
    5217          892 :         start_lsn: Lsn,
    5218          892 :         ancestor: Option<Arc<Timeline>>,
    5219          892 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    5220          892 :         let tenant_shard_id = self.tenant_shard_id;
    5221          892 : 
    5222          892 :         let resources = self.build_timeline_resources(new_timeline_id);
    5223          892 :         resources
    5224          892 :             .remote_client
    5225          892 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    5226              : 
    5227          892 :         let timeline_struct = self
    5228          892 :             .create_timeline_struct(
    5229          892 :                 new_timeline_id,
    5230          892 :                 new_metadata,
    5231          892 :                 None,
    5232          892 :                 ancestor,
    5233          892 :                 resources,
    5234          892 :                 CreateTimelineCause::Load,
    5235          892 :                 create_guard.idempotency.clone(),
    5236          892 :                 None,
    5237          892 :                 None,
    5238          892 :             )
    5239          892 :             .context("Failed to create timeline data structure")?;
    5240              : 
    5241          892 :         timeline_struct.init_empty_layer_map(start_lsn);
    5242              : 
    5243          892 :         if let Err(e) = self
    5244          892 :             .create_timeline_files(&create_guard.timeline_path)
    5245          892 :             .await
    5246              :         {
    5247            0 :             error!(
    5248            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5249              :             );
    5250            0 :             cleanup_timeline_directory(create_guard);
    5251            0 :             return Err(e);
    5252          892 :         }
    5253          892 : 
    5254          892 :         debug!(
    5255            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5256              :         );
    5257              : 
    5258          892 :         Ok(UninitializedTimeline::new(
    5259          892 :             self,
    5260          892 :             new_timeline_id,
    5261          892 :             Some((timeline_struct, create_guard)),
    5262          892 :         ))
    5263          892 :     }
    5264              : 
    5265          892 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5266          892 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5267              : 
    5268          892 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5269            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5270          892 :         });
    5271              : 
    5272          892 :         Ok(())
    5273          892 :     }
    5274              : 
    5275              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5276              :     /// concurrent attempts to create the same timeline.
    5277              :     ///
    5278              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5279              :     /// offloaded timelines or not.
    5280          904 :     fn create_timeline_create_guard(
    5281          904 :         self: &Arc<Self>,
    5282          904 :         timeline_id: TimelineId,
    5283          904 :         idempotency: CreateTimelineIdempotency,
    5284          904 :         allow_offloaded: bool,
    5285          904 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5286          904 :         let tenant_shard_id = self.tenant_shard_id;
    5287          904 : 
    5288          904 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5289              : 
    5290          904 :         let create_guard = TimelineCreateGuard::new(
    5291          904 :             self,
    5292          904 :             timeline_id,
    5293          904 :             timeline_path.clone(),
    5294          904 :             idempotency,
    5295          904 :             allow_offloaded,
    5296          904 :         )?;
    5297              : 
    5298              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5299              :         // for creation.
    5300              :         // A timeline directory should never exist on disk already:
    5301              :         // - a previous failed creation would have cleaned up after itself
    5302              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5303              :         //
    5304              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5305              :         // this error may indicate a bug in cleanup on failed creations.
    5306          900 :         if timeline_path.exists() {
    5307            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5308            0 :                 "Timeline directory already exists! This is a bug."
    5309            0 :             )));
    5310          900 :         }
    5311          900 : 
    5312          900 :         Ok(create_guard)
    5313          904 :     }
    5314              : 
    5315              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5316              :     ///
    5317              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5318              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5319              :     pub async fn gather_size_inputs(
    5320              :         &self,
    5321              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5322              :         // (only if it is shorter than the real cutoff).
    5323              :         max_retention_period: Option<u64>,
    5324              :         cause: LogicalSizeCalculationCause,
    5325              :         cancel: &CancellationToken,
    5326              :         ctx: &RequestContext,
    5327              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5328              :         let logical_sizes_at_once = self
    5329              :             .conf
    5330              :             .concurrent_tenant_size_logical_size_queries
    5331              :             .inner();
    5332              : 
    5333              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5334              :         //
    5335              :         // But the only case where we need to run multiple of these at once is when we
    5336              :         // request a size for a tenant manually via API, while another background calculation
    5337              :         // is in progress (which is not a common case).
    5338              :         //
    5339              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5340              :         let mut shared_cache = tokio::select! {
    5341              :             locked = self.cached_logical_sizes.lock() => locked,
    5342              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5343              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5344              :         };
    5345              : 
    5346              :         size::gather_inputs(
    5347              :             self,
    5348              :             logical_sizes_at_once,
    5349              :             max_retention_period,
    5350              :             &mut shared_cache,
    5351              :             cause,
    5352              :             cancel,
    5353              :             ctx,
    5354              :         )
    5355              :         .await
    5356              :     }
    5357              : 
    5358              :     /// Calculate synthetic tenant size and cache the result.
    5359              :     /// This is periodically called by background worker.
    5360              :     /// result is cached in tenant struct
    5361              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5362              :     pub async fn calculate_synthetic_size(
    5363              :         &self,
    5364              :         cause: LogicalSizeCalculationCause,
    5365              :         cancel: &CancellationToken,
    5366              :         ctx: &RequestContext,
    5367              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5368              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5369              : 
    5370              :         let size = inputs.calculate();
    5371              : 
    5372              :         self.set_cached_synthetic_size(size);
    5373              : 
    5374              :         Ok(size)
    5375              :     }
    5376              : 
    5377              :     /// Cache given synthetic size and update the metric value
    5378            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5379            0 :         self.cached_synthetic_tenant_size
    5380            0 :             .store(size, Ordering::Relaxed);
    5381            0 : 
    5382            0 :         // Only shard zero should be calculating synthetic sizes
    5383            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5384              : 
    5385            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5386            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5387            0 :             .unwrap()
    5388            0 :             .set(size);
    5389            0 :     }
    5390              : 
    5391            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5392            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5393            0 :     }
    5394              : 
    5395              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5396              :     ///
    5397              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5398              :     /// from an external API handler.
    5399              :     ///
    5400              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5401              :     /// still bounded by tenant/timeline shutdown.
    5402              :     #[tracing::instrument(skip_all)]
    5403              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5404              :         let timelines = self.timelines.lock().unwrap().clone();
    5405              : 
    5406            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5407            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5408            0 :             timeline.freeze_and_flush().await?;
    5409            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5410            0 :             timeline.remote_client.wait_completion().await?;
    5411              : 
    5412            0 :             Ok(())
    5413            0 :         }
    5414              : 
    5415              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5416              :         // aborted when this function's future is cancelled: they should stay alive
    5417              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5418              :         // before Timeline shutdown completes.
    5419              :         let mut results = FuturesUnordered::new();
    5420              : 
    5421              :         for (_timeline_id, timeline) in timelines {
    5422              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5423              :             // means that if this function's future is cancelled, the Timeline shutdown
    5424              :             // will still wait for any I/O in here to complete.
    5425              :             let Ok(gate) = timeline.gate.enter() else {
    5426              :                 continue;
    5427              :             };
    5428            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5429              :             results.push(jh);
    5430              :         }
    5431              : 
    5432              :         while let Some(r) = results.next().await {
    5433              :             if let Err(e) = r {
    5434              :                 if !e.is_cancelled() && !e.is_panic() {
    5435              :                     tracing::error!("unexpected join error: {e:?}");
    5436              :                 }
    5437              :             }
    5438              :         }
    5439              : 
    5440              :         // The flushes we did above were just writes, but the Tenant might have had
    5441              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5442              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5443              :         // because it's typically a no-op.
    5444              :         match self.deletion_queue_client.flush_execute().await {
    5445              :             Ok(_) => {}
    5446              :             Err(DeletionQueueError::ShuttingDown) => {}
    5447              :         }
    5448              : 
    5449              :         Ok(())
    5450              :     }
    5451              : 
    5452            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5453            0 :         self.tenant_conf.load().tenant_conf.clone()
    5454            0 :     }
    5455              : 
    5456              :     /// How much local storage would this tenant like to have?  It can cope with
    5457              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5458              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5459              :     /// by keeping important things on local disk.
    5460              :     ///
    5461              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5462              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5463              :     /// actually use more than they report here.
    5464            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5465            0 :         let timelines = self.timelines.lock().unwrap();
    5466            0 : 
    5467            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5468            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5469            0 :         // of them is used actively enough to occupy space on disk.
    5470            0 :         timelines
    5471            0 :             .values()
    5472            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5473            0 :             .max()
    5474            0 :             .unwrap_or(0)
    5475            0 :     }
    5476              : 
    5477              :     /// Serialize and write the latest TenantManifest to remote storage.
    5478            4 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5479              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5480              :         // must be loaded while holding this lock. This makes it safe to call this function
    5481              :         // from anywhere without worrying about colliding updates.
    5482            4 :         let mut guard = tokio::select! {
    5483            4 :             g = self.tenant_manifest_upload.lock() => {
    5484            4 :                 g
    5485              :             },
    5486            4 :             _ = self.cancel.cancelled() => {
    5487            0 :                 return Err(TenantManifestError::Cancelled);
    5488              :             }
    5489              :         };
    5490              : 
    5491            4 :         let manifest = self.build_tenant_manifest();
    5492            4 :         if Some(&manifest) == (*guard).as_ref() {
    5493              :             // Optimisation: skip uploads that don't change anything.
    5494            0 :             return Ok(());
    5495            4 :         }
    5496            4 : 
    5497            4 :         // Remote storage does no retries internally, so wrap it
    5498            4 :         match backoff::retry(
    5499            4 :             || async {
    5500            4 :                 upload_tenant_manifest(
    5501            4 :                     &self.remote_storage,
    5502            4 :                     &self.tenant_shard_id,
    5503            4 :                     self.generation,
    5504            4 :                     &manifest,
    5505            4 :                     &self.cancel,
    5506            4 :                 )
    5507            4 :                 .await
    5508            8 :             },
    5509            4 :             |_e| self.cancel.is_cancelled(),
    5510            4 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5511            4 :             FAILED_REMOTE_OP_RETRIES,
    5512            4 :             "uploading tenant manifest",
    5513            4 :             &self.cancel,
    5514            4 :         )
    5515            4 :         .await
    5516              :         {
    5517            0 :             None => Err(TenantManifestError::Cancelled),
    5518            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5519            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5520              :             Some(Ok(_)) => {
    5521              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5522              :                 // re-uploading the same thing.
    5523            4 :                 *guard = Some(manifest);
    5524            4 : 
    5525            4 :                 Ok(())
    5526              :             }
    5527              :         }
    5528            4 :     }
    5529              : }
    5530              : 
    5531              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5532              : /// to get bootstrap data for timeline initialization.
    5533            0 : async fn run_initdb(
    5534            0 :     conf: &'static PageServerConf,
    5535            0 :     initdb_target_dir: &Utf8Path,
    5536            0 :     pg_version: u32,
    5537            0 :     cancel: &CancellationToken,
    5538            0 : ) -> Result<(), InitdbError> {
    5539            0 :     let initdb_bin_path = conf
    5540            0 :         .pg_bin_dir(pg_version)
    5541            0 :         .map_err(InitdbError::Other)?
    5542            0 :         .join("initdb");
    5543            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5544            0 :     info!(
    5545            0 :         "running {} in {}, libdir: {}",
    5546              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5547              :     );
    5548              : 
    5549            0 :     let _permit = {
    5550            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5551            0 :         INIT_DB_SEMAPHORE.acquire().await
    5552              :     };
    5553              : 
    5554            0 :     CONCURRENT_INITDBS.inc();
    5555            0 :     scopeguard::defer! {
    5556            0 :         CONCURRENT_INITDBS.dec();
    5557            0 :     }
    5558            0 : 
    5559            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5560            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5561            0 :         superuser: &conf.superuser,
    5562            0 :         locale: &conf.locale,
    5563            0 :         initdb_bin: &initdb_bin_path,
    5564            0 :         pg_version,
    5565            0 :         library_search_path: &initdb_lib_dir,
    5566            0 :         pgdata: initdb_target_dir,
    5567            0 :     })
    5568            0 :     .await
    5569            0 :     .map_err(InitdbError::Inner);
    5570            0 : 
    5571            0 :     // This isn't true cancellation support, see above. Still return an error to
    5572            0 :     // excercise the cancellation code path.
    5573            0 :     if cancel.is_cancelled() {
    5574            0 :         return Err(InitdbError::Cancelled);
    5575            0 :     }
    5576            0 : 
    5577            0 :     res
    5578            0 : }
    5579              : 
    5580              : /// Dump contents of a layer file to stdout.
    5581            0 : pub async fn dump_layerfile_from_path(
    5582            0 :     path: &Utf8Path,
    5583            0 :     verbose: bool,
    5584            0 :     ctx: &RequestContext,
    5585            0 : ) -> anyhow::Result<()> {
    5586              :     use std::os::unix::fs::FileExt;
    5587              : 
    5588              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5589              :     // file.
    5590            0 :     let file = File::open(path)?;
    5591            0 :     let mut header_buf = [0u8; 2];
    5592            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5593              : 
    5594            0 :     match u16::from_be_bytes(header_buf) {
    5595              :         crate::IMAGE_FILE_MAGIC => {
    5596            0 :             ImageLayer::new_for_path(path, file)?
    5597            0 :                 .dump(verbose, ctx)
    5598            0 :                 .await?
    5599              :         }
    5600              :         crate::DELTA_FILE_MAGIC => {
    5601            0 :             DeltaLayer::new_for_path(path, file)?
    5602            0 :                 .dump(verbose, ctx)
    5603            0 :                 .await?
    5604              :         }
    5605            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5606              :     }
    5607              : 
    5608            0 :     Ok(())
    5609            0 : }
    5610              : 
    5611              : #[cfg(test)]
    5612              : pub(crate) mod harness {
    5613              :     use bytes::{Bytes, BytesMut};
    5614              :     use hex_literal::hex;
    5615              :     use once_cell::sync::OnceCell;
    5616              :     use pageserver_api::key::Key;
    5617              :     use pageserver_api::models::ShardParameters;
    5618              :     use pageserver_api::record::NeonWalRecord;
    5619              :     use pageserver_api::shard::ShardIndex;
    5620              :     use utils::id::TenantId;
    5621              :     use utils::logging;
    5622              : 
    5623              :     use super::*;
    5624              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5625              :     use crate::l0_flush::L0FlushConfig;
    5626              :     use crate::walredo::apply_neon;
    5627              : 
    5628              :     pub const TIMELINE_ID: TimelineId =
    5629              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5630              :     pub const NEW_TIMELINE_ID: TimelineId =
    5631              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5632              : 
    5633              :     /// Convenience function to create a page image with given string as the only content
    5634     10057546 :     pub fn test_img(s: &str) -> Bytes {
    5635     10057546 :         let mut buf = BytesMut::new();
    5636     10057546 :         buf.extend_from_slice(s.as_bytes());
    5637     10057546 :         buf.resize(64, 0);
    5638     10057546 : 
    5639     10057546 :         buf.freeze()
    5640     10057546 :     }
    5641              : 
    5642              :     impl From<TenantConf> for TenantConfOpt {
    5643          452 :         fn from(tenant_conf: TenantConf) -> Self {
    5644          452 :             Self {
    5645          452 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5646          452 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5647          452 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5648          452 :                 compaction_period: Some(tenant_conf.compaction_period),
    5649          452 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5650          452 :                 compaction_upper_limit: Some(tenant_conf.compaction_upper_limit),
    5651          452 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5652          452 :                 compaction_l0_first: Some(tenant_conf.compaction_l0_first),
    5653          452 :                 compaction_l0_semaphore: Some(tenant_conf.compaction_l0_semaphore),
    5654          452 :                 l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
    5655          452 :                 l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
    5656          452 :                 l0_flush_wait_upload: Some(tenant_conf.l0_flush_wait_upload),
    5657          452 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5658          452 :                 gc_period: Some(tenant_conf.gc_period),
    5659          452 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5660          452 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5661          452 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5662          452 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5663          452 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5664          452 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5665          452 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5666          452 :                 evictions_low_residence_duration_metric_threshold: Some(
    5667          452 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5668          452 :                 ),
    5669          452 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5670          452 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5671          452 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5672          452 :                 image_layer_creation_check_threshold: Some(
    5673          452 :                     tenant_conf.image_layer_creation_check_threshold,
    5674          452 :                 ),
    5675          452 :                 image_creation_preempt_threshold: Some(
    5676          452 :                     tenant_conf.image_creation_preempt_threshold,
    5677          452 :                 ),
    5678          452 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5679          452 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5680          452 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5681          452 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5682          452 :                 rel_size_v2_enabled: Some(tenant_conf.rel_size_v2_enabled),
    5683          452 :                 gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
    5684          452 :                 gc_compaction_initial_threshold_kb: Some(
    5685          452 :                     tenant_conf.gc_compaction_initial_threshold_kb,
    5686          452 :                 ),
    5687          452 :                 gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
    5688          452 :             }
    5689          452 :         }
    5690              :     }
    5691              : 
    5692              :     pub struct TenantHarness {
    5693              :         pub conf: &'static PageServerConf,
    5694              :         pub tenant_conf: TenantConf,
    5695              :         pub tenant_shard_id: TenantShardId,
    5696              :         pub generation: Generation,
    5697              :         pub shard: ShardIndex,
    5698              :         pub remote_storage: GenericRemoteStorage,
    5699              :         pub remote_fs_dir: Utf8PathBuf,
    5700              :         pub deletion_queue: MockDeletionQueue,
    5701              :     }
    5702              : 
    5703              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5704              : 
    5705          500 :     pub(crate) fn setup_logging() {
    5706          500 :         LOG_HANDLE.get_or_init(|| {
    5707          476 :             logging::init(
    5708          476 :                 logging::LogFormat::Test,
    5709          476 :                 // enable it in case the tests exercise code paths that use
    5710          476 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5711          476 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5712          476 :                 logging::Output::Stdout,
    5713          476 :             )
    5714          476 :             .expect("Failed to init test logging")
    5715          500 :         });
    5716          500 :     }
    5717              : 
    5718              :     impl TenantHarness {
    5719          452 :         pub async fn create_custom(
    5720          452 :             test_name: &'static str,
    5721          452 :             tenant_conf: TenantConf,
    5722          452 :             tenant_id: TenantId,
    5723          452 :             shard_identity: ShardIdentity,
    5724          452 :             generation: Generation,
    5725          452 :         ) -> anyhow::Result<Self> {
    5726          452 :             setup_logging();
    5727          452 : 
    5728          452 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5729          452 :             let _ = fs::remove_dir_all(&repo_dir);
    5730          452 :             fs::create_dir_all(&repo_dir)?;
    5731              : 
    5732          452 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5733          452 :             // Make a static copy of the config. This can never be free'd, but that's
    5734          452 :             // OK in a test.
    5735          452 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5736          452 : 
    5737          452 :             let shard = shard_identity.shard_index();
    5738          452 :             let tenant_shard_id = TenantShardId {
    5739          452 :                 tenant_id,
    5740          452 :                 shard_number: shard.shard_number,
    5741          452 :                 shard_count: shard.shard_count,
    5742          452 :             };
    5743          452 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5744          452 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5745              : 
    5746              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5747          452 :             let remote_fs_dir = conf.workdir.join("localfs");
    5748          452 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5749          452 :             let config = RemoteStorageConfig {
    5750          452 :                 storage: RemoteStorageKind::LocalFs {
    5751          452 :                     local_path: remote_fs_dir.clone(),
    5752          452 :                 },
    5753          452 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5754          452 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5755          452 :             };
    5756          452 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5757          452 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5758          452 : 
    5759          452 :             Ok(Self {
    5760          452 :                 conf,
    5761          452 :                 tenant_conf,
    5762          452 :                 tenant_shard_id,
    5763          452 :                 generation,
    5764          452 :                 shard,
    5765          452 :                 remote_storage,
    5766          452 :                 remote_fs_dir,
    5767          452 :                 deletion_queue,
    5768          452 :             })
    5769          452 :         }
    5770              : 
    5771          428 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5772          428 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5773          428 :             // The tests perform them manually if needed.
    5774          428 :             let tenant_conf = TenantConf {
    5775          428 :                 gc_period: Duration::ZERO,
    5776          428 :                 compaction_period: Duration::ZERO,
    5777          428 :                 ..TenantConf::default()
    5778          428 :             };
    5779          428 :             let tenant_id = TenantId::generate();
    5780          428 :             let shard = ShardIdentity::unsharded();
    5781          428 :             Self::create_custom(
    5782          428 :                 test_name,
    5783          428 :                 tenant_conf,
    5784          428 :                 tenant_id,
    5785          428 :                 shard,
    5786          428 :                 Generation::new(0xdeadbeef),
    5787          428 :             )
    5788          428 :             .await
    5789          428 :         }
    5790              : 
    5791           40 :         pub fn span(&self) -> tracing::Span {
    5792           40 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5793           40 :         }
    5794              : 
    5795          452 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5796          452 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5797          452 :             (
    5798          452 :                 self.do_try_load(&ctx)
    5799          452 :                     .await
    5800          452 :                     .expect("failed to load test tenant"),
    5801          452 :                 ctx,
    5802          452 :             )
    5803          452 :         }
    5804              : 
    5805              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5806              :         pub(crate) async fn do_try_load(
    5807              :             &self,
    5808              :             ctx: &RequestContext,
    5809              :         ) -> anyhow::Result<Arc<Tenant>> {
    5810              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5811              : 
    5812              :             let tenant = Arc::new(Tenant::new(
    5813              :                 TenantState::Attaching,
    5814              :                 self.conf,
    5815              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5816              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5817              :                     self.generation,
    5818              :                     &ShardParameters::default(),
    5819              :                 ))
    5820              :                 .unwrap(),
    5821              :                 // This is a legacy/test code path: sharding isn't supported here.
    5822              :                 ShardIdentity::unsharded(),
    5823              :                 Some(walredo_mgr),
    5824              :                 self.tenant_shard_id,
    5825              :                 self.remote_storage.clone(),
    5826              :                 self.deletion_queue.new_client(),
    5827              :                 // TODO: ideally we should run all unit tests with both configs
    5828              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5829              :             ));
    5830              : 
    5831              :             let preload = tenant
    5832              :                 .preload(&self.remote_storage, CancellationToken::new())
    5833              :                 .await?;
    5834              :             tenant.attach(Some(preload), ctx).await?;
    5835              : 
    5836              :             tenant.state.send_replace(TenantState::Active);
    5837              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5838              :                 timeline.set_state(TimelineState::Active);
    5839              :             }
    5840              :             Ok(tenant)
    5841              :         }
    5842              : 
    5843            4 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5844            4 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5845            4 :         }
    5846              :     }
    5847              : 
    5848              :     // Mock WAL redo manager that doesn't do much
    5849              :     pub(crate) struct TestRedoManager;
    5850              : 
    5851              :     impl TestRedoManager {
    5852              :         /// # Cancel-Safety
    5853              :         ///
    5854              :         /// This method is cancellation-safe.
    5855         1676 :         pub async fn request_redo(
    5856         1676 :             &self,
    5857         1676 :             key: Key,
    5858         1676 :             lsn: Lsn,
    5859         1676 :             base_img: Option<(Lsn, Bytes)>,
    5860         1676 :             records: Vec<(Lsn, NeonWalRecord)>,
    5861         1676 :             _pg_version: u32,
    5862         1676 :         ) -> Result<Bytes, walredo::Error> {
    5863         2472 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5864         1676 :             if records_neon {
    5865              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5866         1676 :                 let mut page = match (base_img, records.first()) {
    5867         1536 :                     (Some((_lsn, img)), _) => {
    5868         1536 :                         let mut page = BytesMut::new();
    5869         1536 :                         page.extend_from_slice(&img);
    5870         1536 :                         page
    5871              :                     }
    5872          140 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5873              :                     _ => {
    5874            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5875              :                     }
    5876              :                 };
    5877              : 
    5878         4148 :                 for (record_lsn, record) in records {
    5879         2472 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5880              :                 }
    5881         1676 :                 Ok(page.freeze())
    5882              :             } else {
    5883              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5884            0 :                 let s = format!(
    5885            0 :                     "redo for {} to get to {}, with {} and {} records",
    5886            0 :                     key,
    5887            0 :                     lsn,
    5888            0 :                     if base_img.is_some() {
    5889            0 :                         "base image"
    5890              :                     } else {
    5891            0 :                         "no base image"
    5892              :                     },
    5893            0 :                     records.len()
    5894            0 :                 );
    5895            0 :                 println!("{s}");
    5896            0 : 
    5897            0 :                 Ok(test_img(&s))
    5898              :             }
    5899         1676 :         }
    5900              :     }
    5901              : }
    5902              : 
    5903              : #[cfg(test)]
    5904              : mod tests {
    5905              :     use std::collections::{BTreeMap, BTreeSet};
    5906              : 
    5907              :     use bytes::{Bytes, BytesMut};
    5908              :     use hex_literal::hex;
    5909              :     use itertools::Itertools;
    5910              :     #[cfg(feature = "testing")]
    5911              :     use models::CompactLsnRange;
    5912              :     use pageserver_api::key::{AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
    5913              :     use pageserver_api::keyspace::KeySpace;
    5914              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5915              :     #[cfg(feature = "testing")]
    5916              :     use pageserver_api::record::NeonWalRecord;
    5917              :     use pageserver_api::value::Value;
    5918              :     use pageserver_compaction::helpers::overlaps_with;
    5919              :     use rand::{Rng, thread_rng};
    5920              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5921              :     use tests::storage_layer::ValuesReconstructState;
    5922              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5923              :     #[cfg(feature = "testing")]
    5924              :     use timeline::GcInfo;
    5925              :     #[cfg(feature = "testing")]
    5926              :     use timeline::InMemoryLayerTestDesc;
    5927              :     #[cfg(feature = "testing")]
    5928              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5929              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5930              :     use utils::id::TenantId;
    5931              : 
    5932              :     use super::*;
    5933              :     use crate::DEFAULT_PG_VERSION;
    5934              :     use crate::keyspace::KeySpaceAccum;
    5935              :     use crate::tenant::harness::*;
    5936              :     use crate::tenant::timeline::CompactFlags;
    5937              : 
    5938              :     static TEST_KEY: Lazy<Key> =
    5939           36 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5940              : 
    5941              :     #[tokio::test]
    5942            4 :     async fn test_basic() -> anyhow::Result<()> {
    5943            4 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5944            4 :         let tline = tenant
    5945            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5946            4 :             .await?;
    5947            4 : 
    5948            4 :         let mut writer = tline.writer().await;
    5949            4 :         writer
    5950            4 :             .put(
    5951            4 :                 *TEST_KEY,
    5952            4 :                 Lsn(0x10),
    5953            4 :                 &Value::Image(test_img("foo at 0x10")),
    5954            4 :                 &ctx,
    5955            4 :             )
    5956            4 :             .await?;
    5957            4 :         writer.finish_write(Lsn(0x10));
    5958            4 :         drop(writer);
    5959            4 : 
    5960            4 :         let mut writer = tline.writer().await;
    5961            4 :         writer
    5962            4 :             .put(
    5963            4 :                 *TEST_KEY,
    5964            4 :                 Lsn(0x20),
    5965            4 :                 &Value::Image(test_img("foo at 0x20")),
    5966            4 :                 &ctx,
    5967            4 :             )
    5968            4 :             .await?;
    5969            4 :         writer.finish_write(Lsn(0x20));
    5970            4 :         drop(writer);
    5971            4 : 
    5972            4 :         assert_eq!(
    5973            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5974            4 :             test_img("foo at 0x10")
    5975            4 :         );
    5976            4 :         assert_eq!(
    5977            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5978            4 :             test_img("foo at 0x10")
    5979            4 :         );
    5980            4 :         assert_eq!(
    5981            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5982            4 :             test_img("foo at 0x20")
    5983            4 :         );
    5984            4 : 
    5985            4 :         Ok(())
    5986            4 :     }
    5987              : 
    5988              :     #[tokio::test]
    5989            4 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5990            4 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5991            4 :             .await?
    5992            4 :             .load()
    5993            4 :             .await;
    5994            4 :         let _ = tenant
    5995            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5996            4 :             .await?;
    5997            4 : 
    5998            4 :         match tenant
    5999            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6000            4 :             .await
    6001            4 :         {
    6002            4 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6003            4 :             Err(e) => assert_eq!(
    6004            4 :                 e.to_string(),
    6005            4 :                 "timeline already exists with different parameters".to_string()
    6006            4 :             ),
    6007            4 :         }
    6008            4 : 
    6009            4 :         Ok(())
    6010            4 :     }
    6011              : 
    6012              :     /// Convenience function to create a page image with given string as the only content
    6013           20 :     pub fn test_value(s: &str) -> Value {
    6014           20 :         let mut buf = BytesMut::new();
    6015           20 :         buf.extend_from_slice(s.as_bytes());
    6016           20 :         Value::Image(buf.freeze())
    6017           20 :     }
    6018              : 
    6019              :     ///
    6020              :     /// Test branch creation
    6021              :     ///
    6022              :     #[tokio::test]
    6023            4 :     async fn test_branch() -> anyhow::Result<()> {
    6024            4 :         use std::str::from_utf8;
    6025            4 : 
    6026            4 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6027            4 :         let tline = tenant
    6028            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6029            4 :             .await?;
    6030            4 :         let mut writer = tline.writer().await;
    6031            4 : 
    6032            4 :         #[allow(non_snake_case)]
    6033            4 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6034            4 :         #[allow(non_snake_case)]
    6035            4 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6036            4 : 
    6037            4 :         // Insert a value on the timeline
    6038            4 :         writer
    6039            4 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6040            4 :             .await?;
    6041            4 :         writer
    6042            4 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6043            4 :             .await?;
    6044            4 :         writer.finish_write(Lsn(0x20));
    6045            4 : 
    6046            4 :         writer
    6047            4 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6048            4 :             .await?;
    6049            4 :         writer.finish_write(Lsn(0x30));
    6050            4 :         writer
    6051            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6052            4 :             .await?;
    6053            4 :         writer.finish_write(Lsn(0x40));
    6054            4 : 
    6055            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6056            4 : 
    6057            4 :         // Branch the history, modify relation differently on the new timeline
    6058            4 :         tenant
    6059            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6060            4 :             .await?;
    6061            4 :         let newtline = tenant
    6062            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6063            4 :             .expect("Should have a local timeline");
    6064            4 :         let mut new_writer = newtline.writer().await;
    6065            4 :         new_writer
    6066            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6067            4 :             .await?;
    6068            4 :         new_writer.finish_write(Lsn(0x40));
    6069            4 : 
    6070            4 :         // Check page contents on both branches
    6071            4 :         assert_eq!(
    6072            4 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6073            4 :             "foo at 0x40"
    6074            4 :         );
    6075            4 :         assert_eq!(
    6076            4 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6077            4 :             "bar at 0x40"
    6078            4 :         );
    6079            4 :         assert_eq!(
    6080            4 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6081            4 :             "foobar at 0x20"
    6082            4 :         );
    6083            4 : 
    6084            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6085            4 : 
    6086            4 :         Ok(())
    6087            4 :     }
    6088              : 
    6089           40 :     async fn make_some_layers(
    6090           40 :         tline: &Timeline,
    6091           40 :         start_lsn: Lsn,
    6092           40 :         ctx: &RequestContext,
    6093           40 :     ) -> anyhow::Result<()> {
    6094           40 :         let mut lsn = start_lsn;
    6095              :         {
    6096           40 :             let mut writer = tline.writer().await;
    6097              :             // Create a relation on the timeline
    6098           40 :             writer
    6099           40 :                 .put(
    6100           40 :                     *TEST_KEY,
    6101           40 :                     lsn,
    6102           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6103           40 :                     ctx,
    6104           40 :                 )
    6105           40 :                 .await?;
    6106           40 :             writer.finish_write(lsn);
    6107           40 :             lsn += 0x10;
    6108           40 :             writer
    6109           40 :                 .put(
    6110           40 :                     *TEST_KEY,
    6111           40 :                     lsn,
    6112           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6113           40 :                     ctx,
    6114           40 :                 )
    6115           40 :                 .await?;
    6116           40 :             writer.finish_write(lsn);
    6117           40 :             lsn += 0x10;
    6118           40 :         }
    6119           40 :         tline.freeze_and_flush().await?;
    6120              :         {
    6121           40 :             let mut writer = tline.writer().await;
    6122           40 :             writer
    6123           40 :                 .put(
    6124           40 :                     *TEST_KEY,
    6125           40 :                     lsn,
    6126           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6127           40 :                     ctx,
    6128           40 :                 )
    6129           40 :                 .await?;
    6130           40 :             writer.finish_write(lsn);
    6131           40 :             lsn += 0x10;
    6132           40 :             writer
    6133           40 :                 .put(
    6134           40 :                     *TEST_KEY,
    6135           40 :                     lsn,
    6136           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6137           40 :                     ctx,
    6138           40 :                 )
    6139           40 :                 .await?;
    6140           40 :             writer.finish_write(lsn);
    6141           40 :         }
    6142           40 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6143           40 :     }
    6144              : 
    6145              :     #[tokio::test(start_paused = true)]
    6146            4 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6147            4 :         let (tenant, ctx) =
    6148            4 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6149            4 :                 .await?
    6150            4 :                 .load()
    6151            4 :                 .await;
    6152            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6153            4 :         // initial transition into AttachedSingle.
    6154            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6155            4 :         tokio::time::resume();
    6156            4 :         let tline = tenant
    6157            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6158            4 :             .await?;
    6159            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6160            4 : 
    6161            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6162            4 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6163            4 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6164            4 :         // below should fail.
    6165            4 :         tenant
    6166            4 :             .gc_iteration(
    6167            4 :                 Some(TIMELINE_ID),
    6168            4 :                 0x10,
    6169            4 :                 Duration::ZERO,
    6170            4 :                 &CancellationToken::new(),
    6171            4 :                 &ctx,
    6172            4 :             )
    6173            4 :             .await?;
    6174            4 : 
    6175            4 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6176            4 :         match tenant
    6177            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6178            4 :             .await
    6179            4 :         {
    6180            4 :             Ok(_) => panic!("branching should have failed"),
    6181            4 :             Err(err) => {
    6182            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6183            4 :                     panic!("wrong error type")
    6184            4 :                 };
    6185            4 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6186            4 :                 assert!(
    6187            4 :                     err.source()
    6188            4 :                         .unwrap()
    6189            4 :                         .to_string()
    6190            4 :                         .contains("we might've already garbage collected needed data")
    6191            4 :                 )
    6192            4 :             }
    6193            4 :         }
    6194            4 : 
    6195            4 :         Ok(())
    6196            4 :     }
    6197              : 
    6198              :     #[tokio::test]
    6199            4 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6200            4 :         let (tenant, ctx) =
    6201            4 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6202            4 :                 .await?
    6203            4 :                 .load()
    6204            4 :                 .await;
    6205            4 : 
    6206            4 :         let tline = tenant
    6207            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6208            4 :             .await?;
    6209            4 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6210            4 :         match tenant
    6211            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6212            4 :             .await
    6213            4 :         {
    6214            4 :             Ok(_) => panic!("branching should have failed"),
    6215            4 :             Err(err) => {
    6216            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6217            4 :                     panic!("wrong error type");
    6218            4 :                 };
    6219            4 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6220            4 :                 assert!(
    6221            4 :                     &err.source()
    6222            4 :                         .unwrap()
    6223            4 :                         .to_string()
    6224            4 :                         .contains("is earlier than latest GC cutoff")
    6225            4 :                 );
    6226            4 :             }
    6227            4 :         }
    6228            4 : 
    6229            4 :         Ok(())
    6230            4 :     }
    6231              : 
    6232              :     /*
    6233              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6234              :     // remove the old value, we'd need to work a little harder
    6235              :     #[tokio::test]
    6236              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6237              :         let repo =
    6238              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6239              :             .load();
    6240              : 
    6241              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6242              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6243              : 
    6244              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6245              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6246              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6247              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6248              :             Ok(_) => panic!("request for page should have failed"),
    6249              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6250              :         }
    6251              :         Ok(())
    6252              :     }
    6253              :      */
    6254              : 
    6255              :     #[tokio::test]
    6256            4 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6257            4 :         let (tenant, ctx) =
    6258            4 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6259            4 :                 .await?
    6260            4 :                 .load()
    6261            4 :                 .await;
    6262            4 :         let tline = tenant
    6263            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6264            4 :             .await?;
    6265            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6266            4 : 
    6267            4 :         tenant
    6268            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6269            4 :             .await?;
    6270            4 :         let newtline = tenant
    6271            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6272            4 :             .expect("Should have a local timeline");
    6273            4 : 
    6274            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6275            4 : 
    6276            4 :         tline.set_broken("test".to_owned());
    6277            4 : 
    6278            4 :         tenant
    6279            4 :             .gc_iteration(
    6280            4 :                 Some(TIMELINE_ID),
    6281            4 :                 0x10,
    6282            4 :                 Duration::ZERO,
    6283            4 :                 &CancellationToken::new(),
    6284            4 :                 &ctx,
    6285            4 :             )
    6286            4 :             .await?;
    6287            4 : 
    6288            4 :         // The branchpoints should contain all timelines, even ones marked
    6289            4 :         // as Broken.
    6290            4 :         {
    6291            4 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6292            4 :             assert_eq!(branchpoints.len(), 1);
    6293            4 :             assert_eq!(
    6294            4 :                 branchpoints[0],
    6295            4 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6296            4 :             );
    6297            4 :         }
    6298            4 : 
    6299            4 :         // You can read the key from the child branch even though the parent is
    6300            4 :         // Broken, as long as you don't need to access data from the parent.
    6301            4 :         assert_eq!(
    6302            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6303            4 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6304            4 :         );
    6305            4 : 
    6306            4 :         // This needs to traverse to the parent, and fails.
    6307            4 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6308            4 :         assert!(
    6309            4 :             err.to_string().starts_with(&format!(
    6310            4 :                 "bad state on timeline {}: Broken",
    6311            4 :                 tline.timeline_id
    6312            4 :             )),
    6313            4 :             "{err}"
    6314            4 :         );
    6315            4 : 
    6316            4 :         Ok(())
    6317            4 :     }
    6318              : 
    6319              :     #[tokio::test]
    6320            4 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6321            4 :         let (tenant, ctx) =
    6322            4 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6323            4 :                 .await?
    6324            4 :                 .load()
    6325            4 :                 .await;
    6326            4 :         let tline = tenant
    6327            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6328            4 :             .await?;
    6329            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6330            4 : 
    6331            4 :         tenant
    6332            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6333            4 :             .await?;
    6334            4 :         let newtline = tenant
    6335            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6336            4 :             .expect("Should have a local timeline");
    6337            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6338            4 :         tenant
    6339            4 :             .gc_iteration(
    6340            4 :                 Some(TIMELINE_ID),
    6341            4 :                 0x10,
    6342            4 :                 Duration::ZERO,
    6343            4 :                 &CancellationToken::new(),
    6344            4 :                 &ctx,
    6345            4 :             )
    6346            4 :             .await?;
    6347            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6348            4 : 
    6349            4 :         Ok(())
    6350            4 :     }
    6351              :     #[tokio::test]
    6352            4 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6353            4 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6354            4 :             .await?
    6355            4 :             .load()
    6356            4 :             .await;
    6357            4 :         let tline = tenant
    6358            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6359            4 :             .await?;
    6360            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6361            4 : 
    6362            4 :         tenant
    6363            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6364            4 :             .await?;
    6365            4 :         let newtline = tenant
    6366            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6367            4 :             .expect("Should have a local timeline");
    6368            4 : 
    6369            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6370            4 : 
    6371            4 :         // run gc on parent
    6372            4 :         tenant
    6373            4 :             .gc_iteration(
    6374            4 :                 Some(TIMELINE_ID),
    6375            4 :                 0x10,
    6376            4 :                 Duration::ZERO,
    6377            4 :                 &CancellationToken::new(),
    6378            4 :                 &ctx,
    6379            4 :             )
    6380            4 :             .await?;
    6381            4 : 
    6382            4 :         // Check that the data is still accessible on the branch.
    6383            4 :         assert_eq!(
    6384            4 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6385            4 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6386            4 :         );
    6387            4 : 
    6388            4 :         Ok(())
    6389            4 :     }
    6390              : 
    6391              :     #[tokio::test]
    6392            4 :     async fn timeline_load() -> anyhow::Result<()> {
    6393            4 :         const TEST_NAME: &str = "timeline_load";
    6394            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6395            4 :         {
    6396            4 :             let (tenant, ctx) = harness.load().await;
    6397            4 :             let tline = tenant
    6398            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6399            4 :                 .await?;
    6400            4 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6401            4 :             // so that all uploads finish & we can call harness.load() below again
    6402            4 :             tenant
    6403            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6404            4 :                 .instrument(harness.span())
    6405            4 :                 .await
    6406            4 :                 .ok()
    6407            4 :                 .unwrap();
    6408            4 :         }
    6409            4 : 
    6410            4 :         let (tenant, _ctx) = harness.load().await;
    6411            4 :         tenant
    6412            4 :             .get_timeline(TIMELINE_ID, true)
    6413            4 :             .expect("cannot load timeline");
    6414            4 : 
    6415            4 :         Ok(())
    6416            4 :     }
    6417              : 
    6418              :     #[tokio::test]
    6419            4 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6420            4 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6421            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6422            4 :         // create two timelines
    6423            4 :         {
    6424            4 :             let (tenant, ctx) = harness.load().await;
    6425            4 :             let tline = tenant
    6426            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6427            4 :                 .await?;
    6428            4 : 
    6429            4 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6430            4 : 
    6431            4 :             let child_tline = tenant
    6432            4 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6433            4 :                 .await?;
    6434            4 :             child_tline.set_state(TimelineState::Active);
    6435            4 : 
    6436            4 :             let newtline = tenant
    6437            4 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6438            4 :                 .expect("Should have a local timeline");
    6439            4 : 
    6440            4 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6441            4 : 
    6442            4 :             // so that all uploads finish & we can call harness.load() below again
    6443            4 :             tenant
    6444            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6445            4 :                 .instrument(harness.span())
    6446            4 :                 .await
    6447            4 :                 .ok()
    6448            4 :                 .unwrap();
    6449            4 :         }
    6450            4 : 
    6451            4 :         // check that both of them are initially unloaded
    6452            4 :         let (tenant, _ctx) = harness.load().await;
    6453            4 : 
    6454            4 :         // check that both, child and ancestor are loaded
    6455            4 :         let _child_tline = tenant
    6456            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6457            4 :             .expect("cannot get child timeline loaded");
    6458            4 : 
    6459            4 :         let _ancestor_tline = tenant
    6460            4 :             .get_timeline(TIMELINE_ID, true)
    6461            4 :             .expect("cannot get ancestor timeline loaded");
    6462            4 : 
    6463            4 :         Ok(())
    6464            4 :     }
    6465              : 
    6466              :     #[tokio::test]
    6467            4 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6468            4 :         use storage_layer::AsLayerDesc;
    6469            4 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6470            4 :             .await?
    6471            4 :             .load()
    6472            4 :             .await;
    6473            4 :         let tline = tenant
    6474            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6475            4 :             .await?;
    6476            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6477            4 : 
    6478            4 :         let layer_map = tline.layers.read().await;
    6479            4 :         let level0_deltas = layer_map
    6480            4 :             .layer_map()?
    6481            4 :             .level0_deltas()
    6482            4 :             .iter()
    6483            8 :             .map(|desc| layer_map.get_from_desc(desc))
    6484            4 :             .collect::<Vec<_>>();
    6485            4 : 
    6486            4 :         assert!(!level0_deltas.is_empty());
    6487            4 : 
    6488           12 :         for delta in level0_deltas {
    6489            4 :             // Ensure we are dumping a delta layer here
    6490            8 :             assert!(delta.layer_desc().is_delta);
    6491            8 :             delta.dump(true, &ctx).await.unwrap();
    6492            4 :         }
    6493            4 : 
    6494            4 :         Ok(())
    6495            4 :     }
    6496              : 
    6497              :     #[tokio::test]
    6498            4 :     async fn test_images() -> anyhow::Result<()> {
    6499            4 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6500            4 :         let tline = tenant
    6501            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6502            4 :             .await?;
    6503            4 : 
    6504            4 :         let mut writer = tline.writer().await;
    6505            4 :         writer
    6506            4 :             .put(
    6507            4 :                 *TEST_KEY,
    6508            4 :                 Lsn(0x10),
    6509            4 :                 &Value::Image(test_img("foo at 0x10")),
    6510            4 :                 &ctx,
    6511            4 :             )
    6512            4 :             .await?;
    6513            4 :         writer.finish_write(Lsn(0x10));
    6514            4 :         drop(writer);
    6515            4 : 
    6516            4 :         tline.freeze_and_flush().await?;
    6517            4 :         tline
    6518            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6519            4 :             .await?;
    6520            4 : 
    6521            4 :         let mut writer = tline.writer().await;
    6522            4 :         writer
    6523            4 :             .put(
    6524            4 :                 *TEST_KEY,
    6525            4 :                 Lsn(0x20),
    6526            4 :                 &Value::Image(test_img("foo at 0x20")),
    6527            4 :                 &ctx,
    6528            4 :             )
    6529            4 :             .await?;
    6530            4 :         writer.finish_write(Lsn(0x20));
    6531            4 :         drop(writer);
    6532            4 : 
    6533            4 :         tline.freeze_and_flush().await?;
    6534            4 :         tline
    6535            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6536            4 :             .await?;
    6537            4 : 
    6538            4 :         let mut writer = tline.writer().await;
    6539            4 :         writer
    6540            4 :             .put(
    6541            4 :                 *TEST_KEY,
    6542            4 :                 Lsn(0x30),
    6543            4 :                 &Value::Image(test_img("foo at 0x30")),
    6544            4 :                 &ctx,
    6545            4 :             )
    6546            4 :             .await?;
    6547            4 :         writer.finish_write(Lsn(0x30));
    6548            4 :         drop(writer);
    6549            4 : 
    6550            4 :         tline.freeze_and_flush().await?;
    6551            4 :         tline
    6552            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6553            4 :             .await?;
    6554            4 : 
    6555            4 :         let mut writer = tline.writer().await;
    6556            4 :         writer
    6557            4 :             .put(
    6558            4 :                 *TEST_KEY,
    6559            4 :                 Lsn(0x40),
    6560            4 :                 &Value::Image(test_img("foo at 0x40")),
    6561            4 :                 &ctx,
    6562            4 :             )
    6563            4 :             .await?;
    6564            4 :         writer.finish_write(Lsn(0x40));
    6565            4 :         drop(writer);
    6566            4 : 
    6567            4 :         tline.freeze_and_flush().await?;
    6568            4 :         tline
    6569            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6570            4 :             .await?;
    6571            4 : 
    6572            4 :         assert_eq!(
    6573            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6574            4 :             test_img("foo at 0x10")
    6575            4 :         );
    6576            4 :         assert_eq!(
    6577            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6578            4 :             test_img("foo at 0x10")
    6579            4 :         );
    6580            4 :         assert_eq!(
    6581            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6582            4 :             test_img("foo at 0x20")
    6583            4 :         );
    6584            4 :         assert_eq!(
    6585            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6586            4 :             test_img("foo at 0x30")
    6587            4 :         );
    6588            4 :         assert_eq!(
    6589            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6590            4 :             test_img("foo at 0x40")
    6591            4 :         );
    6592            4 : 
    6593            4 :         Ok(())
    6594            4 :     }
    6595              : 
    6596            8 :     async fn bulk_insert_compact_gc(
    6597            8 :         tenant: &Tenant,
    6598            8 :         timeline: &Arc<Timeline>,
    6599            8 :         ctx: &RequestContext,
    6600            8 :         lsn: Lsn,
    6601            8 :         repeat: usize,
    6602            8 :         key_count: usize,
    6603            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6604            8 :         let compact = true;
    6605            8 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6606            8 :     }
    6607              : 
    6608           16 :     async fn bulk_insert_maybe_compact_gc(
    6609           16 :         tenant: &Tenant,
    6610           16 :         timeline: &Arc<Timeline>,
    6611           16 :         ctx: &RequestContext,
    6612           16 :         mut lsn: Lsn,
    6613           16 :         repeat: usize,
    6614           16 :         key_count: usize,
    6615           16 :         compact: bool,
    6616           16 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6617           16 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6618           16 : 
    6619           16 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6620           16 :         let mut blknum = 0;
    6621           16 : 
    6622           16 :         // Enforce that key range is monotonously increasing
    6623           16 :         let mut keyspace = KeySpaceAccum::new();
    6624           16 : 
    6625           16 :         let cancel = CancellationToken::new();
    6626           16 : 
    6627           16 :         for _ in 0..repeat {
    6628          800 :             for _ in 0..key_count {
    6629      8000000 :                 test_key.field6 = blknum;
    6630      8000000 :                 let mut writer = timeline.writer().await;
    6631      8000000 :                 writer
    6632      8000000 :                     .put(
    6633      8000000 :                         test_key,
    6634      8000000 :                         lsn,
    6635      8000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6636      8000000 :                         ctx,
    6637      8000000 :                     )
    6638      8000000 :                     .await?;
    6639      8000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6640      8000000 :                 writer.finish_write(lsn);
    6641      8000000 :                 drop(writer);
    6642      8000000 : 
    6643      8000000 :                 keyspace.add_key(test_key);
    6644      8000000 : 
    6645      8000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6646      8000000 :                 blknum += 1;
    6647              :             }
    6648              : 
    6649          800 :             timeline.freeze_and_flush().await?;
    6650          800 :             if compact {
    6651              :                 // this requires timeline to be &Arc<Timeline>
    6652          400 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6653          400 :             }
    6654              : 
    6655              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6656              :             // originally was.
    6657          800 :             let res = tenant
    6658          800 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6659          800 :                 .await?;
    6660              : 
    6661          800 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6662              :         }
    6663              : 
    6664           16 :         Ok(inserted)
    6665           16 :     }
    6666              : 
    6667              :     //
    6668              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6669              :     // Repeat 50 times.
    6670              :     //
    6671              :     #[tokio::test]
    6672            4 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6673            4 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6674            4 :         let (tenant, ctx) = harness.load().await;
    6675            4 :         let tline = tenant
    6676            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6677            4 :             .await?;
    6678            4 : 
    6679            4 :         let lsn = Lsn(0x10);
    6680            4 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6681            4 : 
    6682            4 :         Ok(())
    6683            4 :     }
    6684              : 
    6685              :     // Test the vectored get real implementation against a simple sequential implementation.
    6686              :     //
    6687              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6688              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6689              :     // grow to the right on the X axis.
    6690              :     //                       [Delta]
    6691              :     //                 [Delta]
    6692              :     //           [Delta]
    6693              :     //    [Delta]
    6694              :     // ------------ Image ---------------
    6695              :     //
    6696              :     // After layer generation we pick the ranges to query as follows:
    6697              :     // 1. The beginning of each delta layer
    6698              :     // 2. At the seam between two adjacent delta layers
    6699              :     //
    6700              :     // There's one major downside to this test: delta layers only contains images,
    6701              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6702              :     #[tokio::test]
    6703            4 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6704            4 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6705            4 :         let (tenant, ctx) = harness.load().await;
    6706            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6707            4 :         let tline = tenant
    6708            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6709            4 :             .await?;
    6710            4 : 
    6711            4 :         let lsn = Lsn(0x10);
    6712            4 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6713            4 : 
    6714            4 :         let guard = tline.layers.read().await;
    6715            4 :         let lm = guard.layer_map()?;
    6716            4 : 
    6717            4 :         lm.dump(true, &ctx).await?;
    6718            4 : 
    6719            4 :         let mut reads = Vec::new();
    6720            4 :         let mut prev = None;
    6721           24 :         lm.iter_historic_layers().for_each(|desc| {
    6722           24 :             if !desc.is_delta() {
    6723            4 :                 prev = Some(desc.clone());
    6724            4 :                 return;
    6725           20 :             }
    6726           20 : 
    6727           20 :             let start = desc.key_range.start;
    6728           20 :             let end = desc
    6729           20 :                 .key_range
    6730           20 :                 .start
    6731           20 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6732           20 :             reads.push(KeySpace {
    6733           20 :                 ranges: vec![start..end],
    6734           20 :             });
    6735            4 : 
    6736           20 :             if let Some(prev) = &prev {
    6737           20 :                 if !prev.is_delta() {
    6738           20 :                     return;
    6739            4 :                 }
    6740            0 : 
    6741            0 :                 let first_range = Key {
    6742            0 :                     field6: prev.key_range.end.field6 - 4,
    6743            0 :                     ..prev.key_range.end
    6744            0 :                 }..prev.key_range.end;
    6745            0 : 
    6746            0 :                 let second_range = desc.key_range.start..Key {
    6747            0 :                     field6: desc.key_range.start.field6 + 4,
    6748            0 :                     ..desc.key_range.start
    6749            0 :                 };
    6750            0 : 
    6751            0 :                 reads.push(KeySpace {
    6752            0 :                     ranges: vec![first_range, second_range],
    6753            0 :                 });
    6754            4 :             };
    6755            4 : 
    6756            4 :             prev = Some(desc.clone());
    6757           24 :         });
    6758            4 : 
    6759            4 :         drop(guard);
    6760            4 : 
    6761            4 :         // Pick a big LSN such that we query over all the changes.
    6762            4 :         let reads_lsn = Lsn(u64::MAX - 1);
    6763            4 : 
    6764           24 :         for read in reads {
    6765           20 :             info!("Doing vectored read on {:?}", read);
    6766            4 : 
    6767           20 :             let vectored_res = tline
    6768           20 :                 .get_vectored_impl(
    6769           20 :                     read.clone(),
    6770           20 :                     reads_lsn,
    6771           20 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    6772           20 :                     &ctx,
    6773           20 :                 )
    6774           20 :                 .await;
    6775            4 : 
    6776           20 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6777           20 :             let mut expect_missing = false;
    6778           20 :             let mut key = read.start().unwrap();
    6779          660 :             while key != read.end().unwrap() {
    6780          640 :                 if let Some(lsns) = inserted.get(&key) {
    6781          640 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6782          640 :                     match expected_lsn {
    6783          640 :                         Some(lsn) => {
    6784          640 :                             expected_lsns.insert(key, *lsn);
    6785          640 :                         }
    6786            4 :                         None => {
    6787            4 :                             expect_missing = true;
    6788            0 :                             break;
    6789            4 :                         }
    6790            4 :                     }
    6791            4 :                 } else {
    6792            4 :                     expect_missing = true;
    6793            0 :                     break;
    6794            4 :                 }
    6795            4 : 
    6796          640 :                 key = key.next();
    6797            4 :             }
    6798            4 : 
    6799           20 :             if expect_missing {
    6800            4 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6801            4 :             } else {
    6802          640 :                 for (key, image) in vectored_res? {
    6803          640 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6804          640 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6805          640 :                     assert_eq!(image?, expected_image);
    6806            4 :                 }
    6807            4 :             }
    6808            4 :         }
    6809            4 : 
    6810            4 :         Ok(())
    6811            4 :     }
    6812              : 
    6813              :     #[tokio::test]
    6814            4 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6815            4 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6816            4 : 
    6817            4 :         let (tenant, ctx) = harness.load().await;
    6818            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6819            4 :         let tline = tenant
    6820            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6821            4 :             .await?;
    6822            4 :         let tline = tline.raw_timeline().unwrap();
    6823            4 : 
    6824            4 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6825            4 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6826            4 :         modification.set_lsn(Lsn(0x1008))?;
    6827            4 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6828            4 :         modification.commit(&ctx).await?;
    6829            4 : 
    6830            4 :         let child_timeline_id = TimelineId::generate();
    6831            4 :         tenant
    6832            4 :             .branch_timeline_test(
    6833            4 :                 tline,
    6834            4 :                 child_timeline_id,
    6835            4 :                 Some(tline.get_last_record_lsn()),
    6836            4 :                 &ctx,
    6837            4 :             )
    6838            4 :             .await?;
    6839            4 : 
    6840            4 :         let child_timeline = tenant
    6841            4 :             .get_timeline(child_timeline_id, true)
    6842            4 :             .expect("Should have the branched timeline");
    6843            4 : 
    6844            4 :         let aux_keyspace = KeySpace {
    6845            4 :             ranges: vec![NON_INHERITED_RANGE],
    6846            4 :         };
    6847            4 :         let read_lsn = child_timeline.get_last_record_lsn();
    6848            4 : 
    6849            4 :         let vectored_res = child_timeline
    6850            4 :             .get_vectored_impl(
    6851            4 :                 aux_keyspace.clone(),
    6852            4 :                 read_lsn,
    6853            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6854            4 :                 &ctx,
    6855            4 :             )
    6856            4 :             .await;
    6857            4 : 
    6858            4 :         let images = vectored_res?;
    6859            4 :         assert!(images.is_empty());
    6860            4 :         Ok(())
    6861            4 :     }
    6862              : 
    6863              :     // Test that vectored get handles layer gaps correctly
    6864              :     // by advancing into the next ancestor timeline if required.
    6865              :     //
    6866              :     // The test generates timelines that look like the diagram below.
    6867              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6868              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6869              :     //
    6870              :     // ```
    6871              :     //-------------------------------+
    6872              :     //                          ...  |
    6873              :     //               [   L1   ]      |
    6874              :     //     [ / L1   ]                | Child Timeline
    6875              :     // ...                           |
    6876              :     // ------------------------------+
    6877              :     //     [ X L1   ]                | Parent Timeline
    6878              :     // ------------------------------+
    6879              :     // ```
    6880              :     #[tokio::test]
    6881            4 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6882            4 :         let tenant_conf = TenantConf {
    6883            4 :             // Make compaction deterministic
    6884            4 :             gc_period: Duration::ZERO,
    6885            4 :             compaction_period: Duration::ZERO,
    6886            4 :             // Encourage creation of L1 layers
    6887            4 :             checkpoint_distance: 16 * 1024,
    6888            4 :             compaction_target_size: 8 * 1024,
    6889            4 :             ..TenantConf::default()
    6890            4 :         };
    6891            4 : 
    6892            4 :         let harness = TenantHarness::create_custom(
    6893            4 :             "test_get_vectored_key_gap",
    6894            4 :             tenant_conf,
    6895            4 :             TenantId::generate(),
    6896            4 :             ShardIdentity::unsharded(),
    6897            4 :             Generation::new(0xdeadbeef),
    6898            4 :         )
    6899            4 :         .await?;
    6900            4 :         let (tenant, ctx) = harness.load().await;
    6901            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6902            4 : 
    6903            4 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6904            4 :         let gap_at_key = current_key.add(100);
    6905            4 :         let mut current_lsn = Lsn(0x10);
    6906            4 : 
    6907            4 :         const KEY_COUNT: usize = 10_000;
    6908            4 : 
    6909            4 :         let timeline_id = TimelineId::generate();
    6910            4 :         let current_timeline = tenant
    6911            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6912            4 :             .await?;
    6913            4 : 
    6914            4 :         current_lsn += 0x100;
    6915            4 : 
    6916            4 :         let mut writer = current_timeline.writer().await;
    6917            4 :         writer
    6918            4 :             .put(
    6919            4 :                 gap_at_key,
    6920            4 :                 current_lsn,
    6921            4 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6922            4 :                 &ctx,
    6923            4 :             )
    6924            4 :             .await?;
    6925            4 :         writer.finish_write(current_lsn);
    6926            4 :         drop(writer);
    6927            4 : 
    6928            4 :         let mut latest_lsns = HashMap::new();
    6929            4 :         latest_lsns.insert(gap_at_key, current_lsn);
    6930            4 : 
    6931            4 :         current_timeline.freeze_and_flush().await?;
    6932            4 : 
    6933            4 :         let child_timeline_id = TimelineId::generate();
    6934            4 : 
    6935            4 :         tenant
    6936            4 :             .branch_timeline_test(
    6937            4 :                 &current_timeline,
    6938            4 :                 child_timeline_id,
    6939            4 :                 Some(current_lsn),
    6940            4 :                 &ctx,
    6941            4 :             )
    6942            4 :             .await?;
    6943            4 :         let child_timeline = tenant
    6944            4 :             .get_timeline(child_timeline_id, true)
    6945            4 :             .expect("Should have the branched timeline");
    6946            4 : 
    6947        40004 :         for i in 0..KEY_COUNT {
    6948        40000 :             if current_key == gap_at_key {
    6949            4 :                 current_key = current_key.next();
    6950            4 :                 continue;
    6951        39996 :             }
    6952        39996 : 
    6953        39996 :             current_lsn += 0x10;
    6954            4 : 
    6955        39996 :             let mut writer = child_timeline.writer().await;
    6956        39996 :             writer
    6957        39996 :                 .put(
    6958        39996 :                     current_key,
    6959        39996 :                     current_lsn,
    6960        39996 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6961        39996 :                     &ctx,
    6962        39996 :                 )
    6963        39996 :                 .await?;
    6964        39996 :             writer.finish_write(current_lsn);
    6965        39996 :             drop(writer);
    6966        39996 : 
    6967        39996 :             latest_lsns.insert(current_key, current_lsn);
    6968        39996 :             current_key = current_key.next();
    6969        39996 : 
    6970        39996 :             // Flush every now and then to encourage layer file creation.
    6971        39996 :             if i % 500 == 0 {
    6972           80 :                 child_timeline.freeze_and_flush().await?;
    6973        39916 :             }
    6974            4 :         }
    6975            4 : 
    6976            4 :         child_timeline.freeze_and_flush().await?;
    6977            4 :         let mut flags = EnumSet::new();
    6978            4 :         flags.insert(CompactFlags::ForceRepartition);
    6979            4 :         child_timeline
    6980            4 :             .compact(&CancellationToken::new(), flags, &ctx)
    6981            4 :             .await?;
    6982            4 : 
    6983            4 :         let key_near_end = {
    6984            4 :             let mut tmp = current_key;
    6985            4 :             tmp.field6 -= 10;
    6986            4 :             tmp
    6987            4 :         };
    6988            4 : 
    6989            4 :         let key_near_gap = {
    6990            4 :             let mut tmp = gap_at_key;
    6991            4 :             tmp.field6 -= 10;
    6992            4 :             tmp
    6993            4 :         };
    6994            4 : 
    6995            4 :         let read = KeySpace {
    6996            4 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6997            4 :         };
    6998            4 :         let results = child_timeline
    6999            4 :             .get_vectored_impl(
    7000            4 :                 read.clone(),
    7001            4 :                 current_lsn,
    7002            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7003            4 :                 &ctx,
    7004            4 :             )
    7005            4 :             .await?;
    7006            4 : 
    7007           88 :         for (key, img_res) in results {
    7008           84 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7009           84 :             assert_eq!(img_res?, expected);
    7010            4 :         }
    7011            4 : 
    7012            4 :         Ok(())
    7013            4 :     }
    7014              : 
    7015              :     // Test that vectored get descends into ancestor timelines correctly and
    7016              :     // does not return an image that's newer than requested.
    7017              :     //
    7018              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7019              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7020              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7021              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7022              :     // order to avoid returning an image that's too new. The test below constructs such
    7023              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7024              :     // ```
    7025              :     //    LSN
    7026              :     //     ^
    7027              :     //     |
    7028              :     //     |
    7029              :     // 500 | --------------------------------------> branch point
    7030              :     // 400 |        X
    7031              :     // 300 |        X
    7032              :     // 200 | --------------------------------------> requested lsn
    7033              :     // 100 |        X
    7034              :     //     |---------------------------------------> Key
    7035              :     //              |
    7036              :     //              ------> requested key
    7037              :     //
    7038              :     // Legend:
    7039              :     // * X - page images
    7040              :     // ```
    7041              :     #[tokio::test]
    7042            4 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7043            4 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7044            4 :         let (tenant, ctx) = harness.load().await;
    7045            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7046            4 : 
    7047            4 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7048            4 :         let end_key = start_key.add(1000);
    7049            4 :         let child_gap_at_key = start_key.add(500);
    7050            4 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7051            4 : 
    7052            4 :         let mut current_lsn = Lsn(0x10);
    7053            4 : 
    7054            4 :         let timeline_id = TimelineId::generate();
    7055            4 :         let parent_timeline = tenant
    7056            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7057            4 :             .await?;
    7058            4 : 
    7059            4 :         current_lsn += 0x100;
    7060            4 : 
    7061           16 :         for _ in 0..3 {
    7062           12 :             let mut key = start_key;
    7063        12012 :             while key < end_key {
    7064        12000 :                 current_lsn += 0x10;
    7065        12000 : 
    7066        12000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    7067            4 : 
    7068        12000 :                 let mut writer = parent_timeline.writer().await;
    7069        12000 :                 writer
    7070        12000 :                     .put(
    7071        12000 :                         key,
    7072        12000 :                         current_lsn,
    7073        12000 :                         &Value::Image(test_img(&image_value)),
    7074        12000 :                         &ctx,
    7075        12000 :                     )
    7076        12000 :                     .await?;
    7077        12000 :                 writer.finish_write(current_lsn);
    7078        12000 : 
    7079        12000 :                 if key == child_gap_at_key {
    7080           12 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7081        11988 :                 }
    7082            4 : 
    7083        12000 :                 key = key.next();
    7084            4 :             }
    7085            4 : 
    7086           12 :             parent_timeline.freeze_and_flush().await?;
    7087            4 :         }
    7088            4 : 
    7089            4 :         let child_timeline_id = TimelineId::generate();
    7090            4 : 
    7091            4 :         let child_timeline = tenant
    7092            4 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7093            4 :             .await?;
    7094            4 : 
    7095            4 :         let mut key = start_key;
    7096         4004 :         while key < end_key {
    7097         4000 :             if key == child_gap_at_key {
    7098            4 :                 key = key.next();
    7099            4 :                 continue;
    7100         3996 :             }
    7101         3996 : 
    7102         3996 :             current_lsn += 0x10;
    7103            4 : 
    7104         3996 :             let mut writer = child_timeline.writer().await;
    7105         3996 :             writer
    7106         3996 :                 .put(
    7107         3996 :                     key,
    7108         3996 :                     current_lsn,
    7109         3996 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    7110         3996 :                     &ctx,
    7111         3996 :                 )
    7112         3996 :                 .await?;
    7113         3996 :             writer.finish_write(current_lsn);
    7114         3996 : 
    7115         3996 :             key = key.next();
    7116            4 :         }
    7117            4 : 
    7118            4 :         child_timeline.freeze_and_flush().await?;
    7119            4 : 
    7120            4 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7121            4 :         let mut query_lsns = Vec::new();
    7122           12 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7123           72 :             for offset in lsn_offsets {
    7124           60 :                 query_lsns.push(Lsn(image_lsn
    7125           60 :                     .0
    7126           60 :                     .checked_add_signed(offset)
    7127           60 :                     .expect("Shouldn't overflow")));
    7128           60 :             }
    7129            4 :         }
    7130            4 : 
    7131           64 :         for query_lsn in query_lsns {
    7132           60 :             let results = child_timeline
    7133           60 :                 .get_vectored_impl(
    7134           60 :                     KeySpace {
    7135           60 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7136           60 :                     },
    7137           60 :                     query_lsn,
    7138           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7139           60 :                     &ctx,
    7140           60 :                 )
    7141           60 :                 .await;
    7142            4 : 
    7143           60 :             let expected_item = parent_gap_lsns
    7144           60 :                 .iter()
    7145           60 :                 .rev()
    7146          136 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7147           60 : 
    7148           60 :             info!(
    7149            4 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7150            4 :                 query_lsn, expected_item
    7151            4 :             );
    7152            4 : 
    7153           60 :             match expected_item {
    7154           52 :                 Some((_, img_value)) => {
    7155           52 :                     let key_results = results.expect("No vectored get error expected");
    7156           52 :                     let key_result = &key_results[&child_gap_at_key];
    7157           52 :                     let returned_img = key_result
    7158           52 :                         .as_ref()
    7159           52 :                         .expect("No page reconstruct error expected");
    7160           52 : 
    7161           52 :                     info!(
    7162            4 :                         "Vectored read at LSN {} returned image {}",
    7163            0 :                         query_lsn,
    7164            0 :                         std::str::from_utf8(returned_img)?
    7165            4 :                     );
    7166           52 :                     assert_eq!(*returned_img, test_img(img_value));
    7167            4 :                 }
    7168            4 :                 None => {
    7169            8 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7170            4 :                 }
    7171            4 :             }
    7172            4 :         }
    7173            4 : 
    7174            4 :         Ok(())
    7175            4 :     }
    7176              : 
    7177              :     #[tokio::test]
    7178            4 :     async fn test_random_updates() -> anyhow::Result<()> {
    7179            4 :         let names_algorithms = [
    7180            4 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7181            4 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7182            4 :         ];
    7183           12 :         for (name, algorithm) in names_algorithms {
    7184            8 :             test_random_updates_algorithm(name, algorithm).await?;
    7185            4 :         }
    7186            4 :         Ok(())
    7187            4 :     }
    7188              : 
    7189            8 :     async fn test_random_updates_algorithm(
    7190            8 :         name: &'static str,
    7191            8 :         compaction_algorithm: CompactionAlgorithm,
    7192            8 :     ) -> anyhow::Result<()> {
    7193            8 :         let mut harness = TenantHarness::create(name).await?;
    7194            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7195            8 :             kind: compaction_algorithm,
    7196            8 :         };
    7197            8 :         let (tenant, ctx) = harness.load().await;
    7198            8 :         let tline = tenant
    7199            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7200            8 :             .await?;
    7201              : 
    7202              :         const NUM_KEYS: usize = 1000;
    7203            8 :         let cancel = CancellationToken::new();
    7204            8 : 
    7205            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7206            8 :         let mut test_key_end = test_key;
    7207            8 :         test_key_end.field6 = NUM_KEYS as u32;
    7208            8 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7209            8 : 
    7210            8 :         let mut keyspace = KeySpaceAccum::new();
    7211            8 : 
    7212            8 :         // Track when each page was last modified. Used to assert that
    7213            8 :         // a read sees the latest page version.
    7214            8 :         let mut updated = [Lsn(0); NUM_KEYS];
    7215            8 : 
    7216            8 :         let mut lsn = Lsn(0x10);
    7217              :         #[allow(clippy::needless_range_loop)]
    7218         8008 :         for blknum in 0..NUM_KEYS {
    7219         8000 :             lsn = Lsn(lsn.0 + 0x10);
    7220         8000 :             test_key.field6 = blknum as u32;
    7221         8000 :             let mut writer = tline.writer().await;
    7222         8000 :             writer
    7223         8000 :                 .put(
    7224         8000 :                     test_key,
    7225         8000 :                     lsn,
    7226         8000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7227         8000 :                     &ctx,
    7228         8000 :                 )
    7229         8000 :                 .await?;
    7230         8000 :             writer.finish_write(lsn);
    7231         8000 :             updated[blknum] = lsn;
    7232         8000 :             drop(writer);
    7233         8000 : 
    7234         8000 :             keyspace.add_key(test_key);
    7235              :         }
    7236              : 
    7237          408 :         for _ in 0..50 {
    7238       400400 :             for _ in 0..NUM_KEYS {
    7239       400000 :                 lsn = Lsn(lsn.0 + 0x10);
    7240       400000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7241       400000 :                 test_key.field6 = blknum as u32;
    7242       400000 :                 let mut writer = tline.writer().await;
    7243       400000 :                 writer
    7244       400000 :                     .put(
    7245       400000 :                         test_key,
    7246       400000 :                         lsn,
    7247       400000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7248       400000 :                         &ctx,
    7249       400000 :                     )
    7250       400000 :                     .await?;
    7251       400000 :                 writer.finish_write(lsn);
    7252       400000 :                 drop(writer);
    7253       400000 :                 updated[blknum] = lsn;
    7254              :             }
    7255              : 
    7256              :             // Read all the blocks
    7257       400000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7258       400000 :                 test_key.field6 = blknum as u32;
    7259       400000 :                 assert_eq!(
    7260       400000 :                     tline.get(test_key, lsn, &ctx).await?,
    7261       400000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7262              :                 );
    7263              :             }
    7264              : 
    7265              :             // Perform a cycle of flush, and GC
    7266          400 :             tline.freeze_and_flush().await?;
    7267          400 :             tenant
    7268          400 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7269          400 :                 .await?;
    7270              :         }
    7271              : 
    7272            8 :         Ok(())
    7273            8 :     }
    7274              : 
    7275              :     #[tokio::test]
    7276            4 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7277            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7278            4 :             .await?
    7279            4 :             .load()
    7280            4 :             .await;
    7281            4 :         let mut tline = tenant
    7282            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7283            4 :             .await?;
    7284            4 : 
    7285            4 :         const NUM_KEYS: usize = 1000;
    7286            4 : 
    7287            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7288            4 : 
    7289            4 :         let mut keyspace = KeySpaceAccum::new();
    7290            4 : 
    7291            4 :         let cancel = CancellationToken::new();
    7292            4 : 
    7293            4 :         // Track when each page was last modified. Used to assert that
    7294            4 :         // a read sees the latest page version.
    7295            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7296            4 : 
    7297            4 :         let mut lsn = Lsn(0x10);
    7298            4 :         #[allow(clippy::needless_range_loop)]
    7299         4004 :         for blknum in 0..NUM_KEYS {
    7300         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7301         4000 :             test_key.field6 = blknum as u32;
    7302         4000 :             let mut writer = tline.writer().await;
    7303         4000 :             writer
    7304         4000 :                 .put(
    7305         4000 :                     test_key,
    7306         4000 :                     lsn,
    7307         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7308         4000 :                     &ctx,
    7309         4000 :                 )
    7310         4000 :                 .await?;
    7311         4000 :             writer.finish_write(lsn);
    7312         4000 :             updated[blknum] = lsn;
    7313         4000 :             drop(writer);
    7314         4000 : 
    7315         4000 :             keyspace.add_key(test_key);
    7316            4 :         }
    7317            4 : 
    7318          204 :         for _ in 0..50 {
    7319          200 :             let new_tline_id = TimelineId::generate();
    7320          200 :             tenant
    7321          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7322          200 :                 .await?;
    7323          200 :             tline = tenant
    7324          200 :                 .get_timeline(new_tline_id, true)
    7325          200 :                 .expect("Should have the branched timeline");
    7326            4 : 
    7327       200200 :             for _ in 0..NUM_KEYS {
    7328       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7329       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7330       200000 :                 test_key.field6 = blknum as u32;
    7331       200000 :                 let mut writer = tline.writer().await;
    7332       200000 :                 writer
    7333       200000 :                     .put(
    7334       200000 :                         test_key,
    7335       200000 :                         lsn,
    7336       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7337       200000 :                         &ctx,
    7338       200000 :                     )
    7339       200000 :                     .await?;
    7340       200000 :                 println!("updating {} at {}", blknum, lsn);
    7341       200000 :                 writer.finish_write(lsn);
    7342       200000 :                 drop(writer);
    7343       200000 :                 updated[blknum] = lsn;
    7344            4 :             }
    7345            4 : 
    7346            4 :             // Read all the blocks
    7347       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7348       200000 :                 test_key.field6 = blknum as u32;
    7349       200000 :                 assert_eq!(
    7350       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7351       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7352            4 :                 );
    7353            4 :             }
    7354            4 : 
    7355            4 :             // Perform a cycle of flush, compact, and GC
    7356          200 :             tline.freeze_and_flush().await?;
    7357          200 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7358          200 :             tenant
    7359          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7360          200 :                 .await?;
    7361            4 :         }
    7362            4 : 
    7363            4 :         Ok(())
    7364            4 :     }
    7365              : 
    7366              :     #[tokio::test]
    7367            4 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7368            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7369            4 :             .await?
    7370            4 :             .load()
    7371            4 :             .await;
    7372            4 :         let mut tline = tenant
    7373            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7374            4 :             .await?;
    7375            4 : 
    7376            4 :         const NUM_KEYS: usize = 100;
    7377            4 :         const NUM_TLINES: usize = 50;
    7378            4 : 
    7379            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7380            4 :         // Track page mutation lsns across different timelines.
    7381            4 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7382            4 : 
    7383            4 :         let mut lsn = Lsn(0x10);
    7384            4 : 
    7385            4 :         #[allow(clippy::needless_range_loop)]
    7386          204 :         for idx in 0..NUM_TLINES {
    7387          200 :             let new_tline_id = TimelineId::generate();
    7388          200 :             tenant
    7389          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7390          200 :                 .await?;
    7391          200 :             tline = tenant
    7392          200 :                 .get_timeline(new_tline_id, true)
    7393          200 :                 .expect("Should have the branched timeline");
    7394            4 : 
    7395        20200 :             for _ in 0..NUM_KEYS {
    7396        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7397        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7398        20000 :                 test_key.field6 = blknum as u32;
    7399        20000 :                 let mut writer = tline.writer().await;
    7400        20000 :                 writer
    7401        20000 :                     .put(
    7402        20000 :                         test_key,
    7403        20000 :                         lsn,
    7404        20000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7405        20000 :                         &ctx,
    7406        20000 :                     )
    7407        20000 :                     .await?;
    7408        20000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7409        20000 :                 writer.finish_write(lsn);
    7410        20000 :                 drop(writer);
    7411        20000 :                 updated[idx][blknum] = lsn;
    7412            4 :             }
    7413            4 :         }
    7414            4 : 
    7415            4 :         // Read pages from leaf timeline across all ancestors.
    7416          200 :         for (idx, lsns) in updated.iter().enumerate() {
    7417        20000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7418            4 :                 // Skip empty mutations.
    7419        20000 :                 if lsn.0 == 0 {
    7420         7342 :                     continue;
    7421        12658 :                 }
    7422        12658 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7423        12658 :                 test_key.field6 = blknum as u32;
    7424        12658 :                 assert_eq!(
    7425        12658 :                     tline.get(test_key, *lsn, &ctx).await?,
    7426        12658 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7427            4 :                 );
    7428            4 :             }
    7429            4 :         }
    7430            4 :         Ok(())
    7431            4 :     }
    7432              : 
    7433              :     #[tokio::test]
    7434            4 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7435            4 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7436            4 :             .await?
    7437            4 :             .load()
    7438            4 :             .await;
    7439            4 : 
    7440            4 :         let initdb_lsn = Lsn(0x20);
    7441            4 :         let utline = tenant
    7442            4 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7443            4 :             .await?;
    7444            4 :         let tline = utline.raw_timeline().unwrap();
    7445            4 : 
    7446            4 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7447            4 :         tline.maybe_spawn_flush_loop();
    7448            4 : 
    7449            4 :         // Make sure the timeline has the minimum set of required keys for operation.
    7450            4 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7451            4 :         // Except if you `put` at `initdb_lsn`.
    7452            4 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7453            4 :         // It uses `repartition()`, which assumes some keys to be present.
    7454            4 :         // Let's make sure the test timeline can handle that case.
    7455            4 :         {
    7456            4 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7457            4 :             assert_eq!(
    7458            4 :                 timeline::FlushLoopState::Running {
    7459            4 :                     expect_initdb_optimization: false,
    7460            4 :                     initdb_optimization_count: 0,
    7461            4 :                 },
    7462            4 :                 *state
    7463            4 :             );
    7464            4 :             *state = timeline::FlushLoopState::Running {
    7465            4 :                 expect_initdb_optimization: true,
    7466            4 :                 initdb_optimization_count: 0,
    7467            4 :             };
    7468            4 :         }
    7469            4 : 
    7470            4 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7471            4 :         // As explained above, the optimization requires some keys to be present.
    7472            4 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7473            4 :         // This is what `create_test_timeline` does, by the way.
    7474            4 :         let mut modification = tline.begin_modification(initdb_lsn);
    7475            4 :         modification
    7476            4 :             .init_empty_test_timeline()
    7477            4 :             .context("init_empty_test_timeline")?;
    7478            4 :         modification
    7479            4 :             .commit(&ctx)
    7480            4 :             .await
    7481            4 :             .context("commit init_empty_test_timeline modification")?;
    7482            4 : 
    7483            4 :         // Do the flush. The flush code will check the expectations that we set above.
    7484            4 :         tline.freeze_and_flush().await?;
    7485            4 : 
    7486            4 :         // assert freeze_and_flush exercised the initdb optimization
    7487            4 :         {
    7488            4 :             let state = tline.flush_loop_state.lock().unwrap();
    7489            4 :             let timeline::FlushLoopState::Running {
    7490            4 :                 expect_initdb_optimization,
    7491            4 :                 initdb_optimization_count,
    7492            4 :             } = *state
    7493            4 :             else {
    7494            4 :                 panic!("unexpected state: {:?}", *state);
    7495            4 :             };
    7496            4 :             assert!(expect_initdb_optimization);
    7497            4 :             assert!(initdb_optimization_count > 0);
    7498            4 :         }
    7499            4 :         Ok(())
    7500            4 :     }
    7501              : 
    7502              :     #[tokio::test]
    7503            4 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7504            4 :         let name = "test_create_guard_crash";
    7505            4 :         let harness = TenantHarness::create(name).await?;
    7506            4 :         {
    7507            4 :             let (tenant, ctx) = harness.load().await;
    7508            4 :             let tline = tenant
    7509            4 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7510            4 :                 .await?;
    7511            4 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7512            4 :             let raw_tline = tline.raw_timeline().unwrap();
    7513            4 :             raw_tline
    7514            4 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7515            4 :                 .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))
    7516            4 :                 .await;
    7517            4 :             std::mem::forget(tline);
    7518            4 :         }
    7519            4 : 
    7520            4 :         let (tenant, _) = harness.load().await;
    7521            4 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7522            4 :             Ok(_) => panic!("timeline should've been removed during load"),
    7523            4 :             Err(e) => {
    7524            4 :                 assert_eq!(
    7525            4 :                     e,
    7526            4 :                     GetTimelineError::NotFound {
    7527            4 :                         tenant_id: tenant.tenant_shard_id,
    7528            4 :                         timeline_id: TIMELINE_ID,
    7529            4 :                     }
    7530            4 :                 )
    7531            4 :             }
    7532            4 :         }
    7533            4 : 
    7534            4 :         assert!(
    7535            4 :             !harness
    7536            4 :                 .conf
    7537            4 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7538            4 :                 .exists()
    7539            4 :         );
    7540            4 : 
    7541            4 :         Ok(())
    7542            4 :     }
    7543              : 
    7544              :     #[tokio::test]
    7545            4 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7546            4 :         let names_algorithms = [
    7547            4 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7548            4 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7549            4 :         ];
    7550           12 :         for (name, algorithm) in names_algorithms {
    7551            8 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7552            4 :         }
    7553            4 :         Ok(())
    7554            4 :     }
    7555              : 
    7556            8 :     async fn test_read_at_max_lsn_algorithm(
    7557            8 :         name: &'static str,
    7558            8 :         compaction_algorithm: CompactionAlgorithm,
    7559            8 :     ) -> anyhow::Result<()> {
    7560            8 :         let mut harness = TenantHarness::create(name).await?;
    7561            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7562            8 :             kind: compaction_algorithm,
    7563            8 :         };
    7564            8 :         let (tenant, ctx) = harness.load().await;
    7565            8 :         let tline = tenant
    7566            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7567            8 :             .await?;
    7568              : 
    7569            8 :         let lsn = Lsn(0x10);
    7570            8 :         let compact = false;
    7571            8 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7572              : 
    7573            8 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7574            8 :         let read_lsn = Lsn(u64::MAX - 1);
    7575              : 
    7576            8 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7577            8 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7578              : 
    7579            8 :         Ok(())
    7580            8 :     }
    7581              : 
    7582              :     #[tokio::test]
    7583            4 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7584            4 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7585            4 :         let (tenant, ctx) = harness.load().await;
    7586            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7587            4 :         let tline = tenant
    7588            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7589            4 :             .await?;
    7590            4 : 
    7591            4 :         const NUM_KEYS: usize = 1000;
    7592            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7593            4 : 
    7594            4 :         let cancel = CancellationToken::new();
    7595            4 : 
    7596            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7597            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7598            4 :         let mut test_key = base_key;
    7599            4 : 
    7600            4 :         // Track when each page was last modified. Used to assert that
    7601            4 :         // a read sees the latest page version.
    7602            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7603            4 : 
    7604            4 :         let mut lsn = Lsn(0x10);
    7605            4 :         #[allow(clippy::needless_range_loop)]
    7606         4004 :         for blknum in 0..NUM_KEYS {
    7607         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7608         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7609         4000 :             let mut writer = tline.writer().await;
    7610         4000 :             writer
    7611         4000 :                 .put(
    7612         4000 :                     test_key,
    7613         4000 :                     lsn,
    7614         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7615         4000 :                     &ctx,
    7616         4000 :                 )
    7617         4000 :                 .await?;
    7618         4000 :             writer.finish_write(lsn);
    7619         4000 :             updated[blknum] = lsn;
    7620         4000 :             drop(writer);
    7621            4 :         }
    7622            4 : 
    7623            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7624            4 : 
    7625           48 :         for iter in 0..=10 {
    7626            4 :             // Read all the blocks
    7627        44000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7628        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7629        44000 :                 assert_eq!(
    7630        44000 :                     tline.get(test_key, lsn, &ctx).await?,
    7631        44000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7632            4 :                 );
    7633            4 :             }
    7634            4 : 
    7635           44 :             let mut cnt = 0;
    7636        44000 :             for (key, value) in tline
    7637           44 :                 .get_vectored_impl(
    7638           44 :                     keyspace.clone(),
    7639           44 :                     lsn,
    7640           44 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7641           44 :                     &ctx,
    7642           44 :                 )
    7643           44 :                 .await?
    7644            4 :             {
    7645        44000 :                 let blknum = key.field6 as usize;
    7646        44000 :                 let value = value?;
    7647        44000 :                 assert!(blknum % STEP == 0);
    7648        44000 :                 let blknum = blknum / STEP;
    7649        44000 :                 assert_eq!(
    7650        44000 :                     value,
    7651        44000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7652        44000 :                 );
    7653        44000 :                 cnt += 1;
    7654            4 :             }
    7655            4 : 
    7656           44 :             assert_eq!(cnt, NUM_KEYS);
    7657            4 : 
    7658        44044 :             for _ in 0..NUM_KEYS {
    7659        44000 :                 lsn = Lsn(lsn.0 + 0x10);
    7660        44000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7661        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7662        44000 :                 let mut writer = tline.writer().await;
    7663        44000 :                 writer
    7664        44000 :                     .put(
    7665        44000 :                         test_key,
    7666        44000 :                         lsn,
    7667        44000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7668        44000 :                         &ctx,
    7669        44000 :                     )
    7670        44000 :                     .await?;
    7671        44000 :                 writer.finish_write(lsn);
    7672        44000 :                 drop(writer);
    7673        44000 :                 updated[blknum] = lsn;
    7674            4 :             }
    7675            4 : 
    7676            4 :             // Perform two cycles of flush, compact, and GC
    7677          132 :             for round in 0..2 {
    7678           88 :                 tline.freeze_and_flush().await?;
    7679           88 :                 tline
    7680           88 :                     .compact(
    7681           88 :                         &cancel,
    7682           88 :                         if iter % 5 == 0 && round == 0 {
    7683           12 :                             let mut flags = EnumSet::new();
    7684           12 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7685           12 :                             flags.insert(CompactFlags::ForceRepartition);
    7686           12 :                             flags
    7687            4 :                         } else {
    7688           76 :                             EnumSet::empty()
    7689            4 :                         },
    7690           88 :                         &ctx,
    7691           88 :                     )
    7692           88 :                     .await?;
    7693           88 :                 tenant
    7694           88 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7695           88 :                     .await?;
    7696            4 :             }
    7697            4 :         }
    7698            4 : 
    7699            4 :         Ok(())
    7700            4 :     }
    7701              : 
    7702              :     #[tokio::test]
    7703            4 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7704            4 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7705            4 :         let (tenant, ctx) = harness.load().await;
    7706            4 :         let tline = tenant
    7707            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7708            4 :             .await?;
    7709            4 : 
    7710            4 :         let cancel = CancellationToken::new();
    7711            4 : 
    7712            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7713            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7714            4 :         let test_key = base_key;
    7715            4 :         let mut lsn = Lsn(0x10);
    7716            4 : 
    7717           84 :         for _ in 0..20 {
    7718           80 :             lsn = Lsn(lsn.0 + 0x10);
    7719           80 :             let mut writer = tline.writer().await;
    7720           80 :             writer
    7721           80 :                 .put(
    7722           80 :                     test_key,
    7723           80 :                     lsn,
    7724           80 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7725           80 :                     &ctx,
    7726           80 :                 )
    7727           80 :                 .await?;
    7728           80 :             writer.finish_write(lsn);
    7729           80 :             drop(writer);
    7730           80 :             tline.freeze_and_flush().await?; // force create a delta layer
    7731            4 :         }
    7732            4 : 
    7733            4 :         let before_num_l0_delta_files =
    7734            4 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7735            4 : 
    7736            4 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7737            4 : 
    7738            4 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7739            4 : 
    7740            4 :         assert!(
    7741            4 :             after_num_l0_delta_files < before_num_l0_delta_files,
    7742            4 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    7743            4 :         );
    7744            4 : 
    7745            4 :         assert_eq!(
    7746            4 :             tline.get(test_key, lsn, &ctx).await?,
    7747            4 :             test_img(&format!("{} at {}", 0, lsn))
    7748            4 :         );
    7749            4 : 
    7750            4 :         Ok(())
    7751            4 :     }
    7752              : 
    7753              :     #[tokio::test]
    7754            4 :     async fn test_aux_file_e2e() {
    7755            4 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7756            4 : 
    7757            4 :         let (tenant, ctx) = harness.load().await;
    7758            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7759            4 : 
    7760            4 :         let mut lsn = Lsn(0x08);
    7761            4 : 
    7762            4 :         let tline: Arc<Timeline> = tenant
    7763            4 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7764            4 :             .await
    7765            4 :             .unwrap();
    7766            4 : 
    7767            4 :         {
    7768            4 :             lsn += 8;
    7769            4 :             let mut modification = tline.begin_modification(lsn);
    7770            4 :             modification
    7771            4 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7772            4 :                 .await
    7773            4 :                 .unwrap();
    7774            4 :             modification.commit(&ctx).await.unwrap();
    7775            4 :         }
    7776            4 : 
    7777            4 :         // we can read everything from the storage
    7778            4 :         let files = tline
    7779            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7780            4 :             .await
    7781            4 :             .unwrap();
    7782            4 :         assert_eq!(
    7783            4 :             files.get("pg_logical/mappings/test1"),
    7784            4 :             Some(&bytes::Bytes::from_static(b"first"))
    7785            4 :         );
    7786            4 : 
    7787            4 :         {
    7788            4 :             lsn += 8;
    7789            4 :             let mut modification = tline.begin_modification(lsn);
    7790            4 :             modification
    7791            4 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7792            4 :                 .await
    7793            4 :                 .unwrap();
    7794            4 :             modification.commit(&ctx).await.unwrap();
    7795            4 :         }
    7796            4 : 
    7797            4 :         let files = tline
    7798            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7799            4 :             .await
    7800            4 :             .unwrap();
    7801            4 :         assert_eq!(
    7802            4 :             files.get("pg_logical/mappings/test2"),
    7803            4 :             Some(&bytes::Bytes::from_static(b"second"))
    7804            4 :         );
    7805            4 : 
    7806            4 :         let child = tenant
    7807            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7808            4 :             .await
    7809            4 :             .unwrap();
    7810            4 : 
    7811            4 :         let files = child
    7812            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7813            4 :             .await
    7814            4 :             .unwrap();
    7815            4 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7816            4 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7817            4 :     }
    7818              : 
    7819              :     #[tokio::test]
    7820            4 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7821            4 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7822            4 :         let (tenant, ctx) = harness.load().await;
    7823            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7824            4 :         let tline = tenant
    7825            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7826            4 :             .await?;
    7827            4 : 
    7828            4 :         const NUM_KEYS: usize = 1000;
    7829            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7830            4 : 
    7831            4 :         let cancel = CancellationToken::new();
    7832            4 : 
    7833            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7834            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7835            4 :         let mut test_key = base_key;
    7836            4 :         let mut lsn = Lsn(0x10);
    7837            4 : 
    7838           16 :         async fn scan_with_statistics(
    7839           16 :             tline: &Timeline,
    7840           16 :             keyspace: &KeySpace,
    7841           16 :             lsn: Lsn,
    7842           16 :             ctx: &RequestContext,
    7843           16 :             io_concurrency: IoConcurrency,
    7844           16 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7845           16 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    7846           16 :             let res = tline
    7847           16 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7848           16 :                 .await?;
    7849           16 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7850           16 :         }
    7851            4 : 
    7852            4 :         #[allow(clippy::needless_range_loop)]
    7853         4004 :         for blknum in 0..NUM_KEYS {
    7854         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7855         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7856         4000 :             let mut writer = tline.writer().await;
    7857         4000 :             writer
    7858         4000 :                 .put(
    7859         4000 :                     test_key,
    7860         4000 :                     lsn,
    7861         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7862         4000 :                     &ctx,
    7863         4000 :                 )
    7864         4000 :                 .await?;
    7865         4000 :             writer.finish_write(lsn);
    7866         4000 :             drop(writer);
    7867            4 :         }
    7868            4 : 
    7869            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7870            4 : 
    7871           44 :         for iter in 1..=10 {
    7872        40040 :             for _ in 0..NUM_KEYS {
    7873        40000 :                 lsn = Lsn(lsn.0 + 0x10);
    7874        40000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7875        40000 :                 test_key.field6 = (blknum * STEP) as u32;
    7876        40000 :                 let mut writer = tline.writer().await;
    7877        40000 :                 writer
    7878        40000 :                     .put(
    7879        40000 :                         test_key,
    7880        40000 :                         lsn,
    7881        40000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7882        40000 :                         &ctx,
    7883        40000 :                     )
    7884        40000 :                     .await?;
    7885        40000 :                 writer.finish_write(lsn);
    7886        40000 :                 drop(writer);
    7887            4 :             }
    7888            4 : 
    7889           40 :             tline.freeze_and_flush().await?;
    7890            4 : 
    7891           40 :             if iter % 5 == 0 {
    7892            8 :                 let (_, before_delta_file_accessed) =
    7893            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7894            8 :                         .await?;
    7895            8 :                 tline
    7896            8 :                     .compact(
    7897            8 :                         &cancel,
    7898            8 :                         {
    7899            8 :                             let mut flags = EnumSet::new();
    7900            8 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7901            8 :                             flags.insert(CompactFlags::ForceRepartition);
    7902            8 :                             flags
    7903            8 :                         },
    7904            8 :                         &ctx,
    7905            8 :                     )
    7906            8 :                     .await?;
    7907            8 :                 let (_, after_delta_file_accessed) =
    7908            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7909            8 :                         .await?;
    7910            8 :                 assert!(
    7911            8 :                     after_delta_file_accessed < before_delta_file_accessed,
    7912            4 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    7913            4 :                 );
    7914            4 :                 // 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.
    7915            8 :                 assert!(
    7916            8 :                     after_delta_file_accessed <= 2,
    7917            4 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7918            4 :                 );
    7919           32 :             }
    7920            4 :         }
    7921            4 : 
    7922            4 :         Ok(())
    7923            4 :     }
    7924              : 
    7925              :     #[tokio::test]
    7926            4 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7927            4 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7928            4 :         let (tenant, ctx) = harness.load().await;
    7929            4 : 
    7930            4 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7931            4 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7932            4 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7933            4 : 
    7934            4 :         let tline = tenant
    7935            4 :             .create_test_timeline_with_layers(
    7936            4 :                 TIMELINE_ID,
    7937            4 :                 Lsn(0x10),
    7938            4 :                 DEFAULT_PG_VERSION,
    7939            4 :                 &ctx,
    7940            4 :                 Vec::new(), // in-memory layers
    7941            4 :                 Vec::new(), // delta layers
    7942            4 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7943            4 :                 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
    7944            4 :             )
    7945            4 :             .await?;
    7946            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7947            4 : 
    7948            4 :         let child = tenant
    7949            4 :             .branch_timeline_test_with_layers(
    7950            4 :                 &tline,
    7951            4 :                 NEW_TIMELINE_ID,
    7952            4 :                 Some(Lsn(0x20)),
    7953            4 :                 &ctx,
    7954            4 :                 Vec::new(), // delta layers
    7955            4 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7956            4 :                 Lsn(0x30),
    7957            4 :             )
    7958            4 :             .await
    7959            4 :             .unwrap();
    7960            4 : 
    7961            4 :         let lsn = Lsn(0x30);
    7962            4 : 
    7963            4 :         // test vectored get on parent timeline
    7964            4 :         assert_eq!(
    7965            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7966            4 :             Some(test_img("data key 1"))
    7967            4 :         );
    7968            4 :         assert!(
    7969            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7970            4 :                 .await
    7971            4 :                 .unwrap_err()
    7972            4 :                 .is_missing_key_error()
    7973            4 :         );
    7974            4 :         assert!(
    7975            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7976            4 :                 .await
    7977            4 :                 .unwrap_err()
    7978            4 :                 .is_missing_key_error()
    7979            4 :         );
    7980            4 : 
    7981            4 :         // test vectored get on child timeline
    7982            4 :         assert_eq!(
    7983            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7984            4 :             Some(test_img("data key 1"))
    7985            4 :         );
    7986            4 :         assert_eq!(
    7987            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7988            4 :             Some(test_img("data key 2"))
    7989            4 :         );
    7990            4 :         assert!(
    7991            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7992            4 :                 .await
    7993            4 :                 .unwrap_err()
    7994            4 :                 .is_missing_key_error()
    7995            4 :         );
    7996            4 : 
    7997            4 :         Ok(())
    7998            4 :     }
    7999              : 
    8000              :     #[tokio::test]
    8001            4 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8002            4 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8003            4 :         let (tenant, ctx) = harness.load().await;
    8004            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8005            4 : 
    8006            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8007            4 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8008            4 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8009            4 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8010            4 : 
    8011            4 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8012            4 :         let base_inherited_key_child =
    8013            4 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8014            4 :         let base_inherited_key_nonexist =
    8015            4 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8016            4 :         let base_inherited_key_overwrite =
    8017            4 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8018            4 : 
    8019            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8020            4 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8021            4 : 
    8022            4 :         let tline = tenant
    8023            4 :             .create_test_timeline_with_layers(
    8024            4 :                 TIMELINE_ID,
    8025            4 :                 Lsn(0x10),
    8026            4 :                 DEFAULT_PG_VERSION,
    8027            4 :                 &ctx,
    8028            4 :                 Vec::new(), // in-memory layers
    8029            4 :                 Vec::new(), // delta layers
    8030            4 :                 vec![(
    8031            4 :                     Lsn(0x20),
    8032            4 :                     vec![
    8033            4 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8034            4 :                         (
    8035            4 :                             base_inherited_key_overwrite,
    8036            4 :                             test_img("metadata key overwrite 1a"),
    8037            4 :                         ),
    8038            4 :                         (base_key, test_img("metadata key 1")),
    8039            4 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8040            4 :                     ],
    8041            4 :                 )], // image layers
    8042            4 :                 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
    8043            4 :             )
    8044            4 :             .await?;
    8045            4 : 
    8046            4 :         let child = tenant
    8047            4 :             .branch_timeline_test_with_layers(
    8048            4 :                 &tline,
    8049            4 :                 NEW_TIMELINE_ID,
    8050            4 :                 Some(Lsn(0x20)),
    8051            4 :                 &ctx,
    8052            4 :                 Vec::new(), // delta layers
    8053            4 :                 vec![(
    8054            4 :                     Lsn(0x30),
    8055            4 :                     vec![
    8056            4 :                         (
    8057            4 :                             base_inherited_key_child,
    8058            4 :                             test_img("metadata inherited key 2"),
    8059            4 :                         ),
    8060            4 :                         (
    8061            4 :                             base_inherited_key_overwrite,
    8062            4 :                             test_img("metadata key overwrite 2a"),
    8063            4 :                         ),
    8064            4 :                         (base_key_child, test_img("metadata key 2")),
    8065            4 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8066            4 :                     ],
    8067            4 :                 )], // image layers
    8068            4 :                 Lsn(0x30),
    8069            4 :             )
    8070            4 :             .await
    8071            4 :             .unwrap();
    8072            4 : 
    8073            4 :         let lsn = Lsn(0x30);
    8074            4 : 
    8075            4 :         // test vectored get on parent timeline
    8076            4 :         assert_eq!(
    8077            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8078            4 :             Some(test_img("metadata key 1"))
    8079            4 :         );
    8080            4 :         assert_eq!(
    8081            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8082            4 :             None
    8083            4 :         );
    8084            4 :         assert_eq!(
    8085            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8086            4 :             None
    8087            4 :         );
    8088            4 :         assert_eq!(
    8089            4 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8090            4 :             Some(test_img("metadata key overwrite 1b"))
    8091            4 :         );
    8092            4 :         assert_eq!(
    8093            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8094            4 :             Some(test_img("metadata inherited key 1"))
    8095            4 :         );
    8096            4 :         assert_eq!(
    8097            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8098            4 :             None
    8099            4 :         );
    8100            4 :         assert_eq!(
    8101            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8102            4 :             None
    8103            4 :         );
    8104            4 :         assert_eq!(
    8105            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8106            4 :             Some(test_img("metadata key overwrite 1a"))
    8107            4 :         );
    8108            4 : 
    8109            4 :         // test vectored get on child timeline
    8110            4 :         assert_eq!(
    8111            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8112            4 :             None
    8113            4 :         );
    8114            4 :         assert_eq!(
    8115            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8116            4 :             Some(test_img("metadata key 2"))
    8117            4 :         );
    8118            4 :         assert_eq!(
    8119            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8120            4 :             None
    8121            4 :         );
    8122            4 :         assert_eq!(
    8123            4 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8124            4 :             Some(test_img("metadata inherited key 1"))
    8125            4 :         );
    8126            4 :         assert_eq!(
    8127            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8128            4 :             Some(test_img("metadata inherited key 2"))
    8129            4 :         );
    8130            4 :         assert_eq!(
    8131            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8132            4 :             None
    8133            4 :         );
    8134            4 :         assert_eq!(
    8135            4 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8136            4 :             Some(test_img("metadata key overwrite 2b"))
    8137            4 :         );
    8138            4 :         assert_eq!(
    8139            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8140            4 :             Some(test_img("metadata key overwrite 2a"))
    8141            4 :         );
    8142            4 : 
    8143            4 :         // test vectored scan on parent timeline
    8144            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8145            4 :         let res = tline
    8146            4 :             .get_vectored_impl(
    8147            4 :                 KeySpace::single(Key::metadata_key_range()),
    8148            4 :                 lsn,
    8149            4 :                 &mut reconstruct_state,
    8150            4 :                 &ctx,
    8151            4 :             )
    8152            4 :             .await?;
    8153            4 : 
    8154            4 :         assert_eq!(
    8155            4 :             res.into_iter()
    8156           16 :                 .map(|(k, v)| (k, v.unwrap()))
    8157            4 :                 .collect::<Vec<_>>(),
    8158            4 :             vec![
    8159            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8160            4 :                 (
    8161            4 :                     base_inherited_key_overwrite,
    8162            4 :                     test_img("metadata key overwrite 1a")
    8163            4 :                 ),
    8164            4 :                 (base_key, test_img("metadata key 1")),
    8165            4 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8166            4 :             ]
    8167            4 :         );
    8168            4 : 
    8169            4 :         // test vectored scan on child timeline
    8170            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8171            4 :         let res = child
    8172            4 :             .get_vectored_impl(
    8173            4 :                 KeySpace::single(Key::metadata_key_range()),
    8174            4 :                 lsn,
    8175            4 :                 &mut reconstruct_state,
    8176            4 :                 &ctx,
    8177            4 :             )
    8178            4 :             .await?;
    8179            4 : 
    8180            4 :         assert_eq!(
    8181            4 :             res.into_iter()
    8182           20 :                 .map(|(k, v)| (k, v.unwrap()))
    8183            4 :                 .collect::<Vec<_>>(),
    8184            4 :             vec![
    8185            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8186            4 :                 (
    8187            4 :                     base_inherited_key_child,
    8188            4 :                     test_img("metadata inherited key 2")
    8189            4 :                 ),
    8190            4 :                 (
    8191            4 :                     base_inherited_key_overwrite,
    8192            4 :                     test_img("metadata key overwrite 2a")
    8193            4 :                 ),
    8194            4 :                 (base_key_child, test_img("metadata key 2")),
    8195            4 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8196            4 :             ]
    8197            4 :         );
    8198            4 : 
    8199            4 :         Ok(())
    8200            4 :     }
    8201              : 
    8202          112 :     async fn get_vectored_impl_wrapper(
    8203          112 :         tline: &Arc<Timeline>,
    8204          112 :         key: Key,
    8205          112 :         lsn: Lsn,
    8206          112 :         ctx: &RequestContext,
    8207          112 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8208          112 :         let io_concurrency =
    8209          112 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    8210          112 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8211          112 :         let mut res = tline
    8212          112 :             .get_vectored_impl(
    8213          112 :                 KeySpace::single(key..key.next()),
    8214          112 :                 lsn,
    8215          112 :                 &mut reconstruct_state,
    8216          112 :                 ctx,
    8217          112 :             )
    8218          112 :             .await?;
    8219          100 :         Ok(res.pop_last().map(|(k, v)| {
    8220           64 :             assert_eq!(k, key);
    8221           64 :             v.unwrap()
    8222          100 :         }))
    8223          112 :     }
    8224              : 
    8225              :     #[tokio::test]
    8226            4 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8227            4 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8228            4 :         let (tenant, ctx) = harness.load().await;
    8229            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8230            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8231            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8232            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8233            4 : 
    8234            4 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8235            4 :         // Lsn 0x30 key0, key3, no key1+key2
    8236            4 :         // Lsn 0x20 key1+key2 tomestones
    8237            4 :         // Lsn 0x10 key1 in image, key2 in delta
    8238            4 :         let tline = tenant
    8239            4 :             .create_test_timeline_with_layers(
    8240            4 :                 TIMELINE_ID,
    8241            4 :                 Lsn(0x10),
    8242            4 :                 DEFAULT_PG_VERSION,
    8243            4 :                 &ctx,
    8244            4 :                 Vec::new(), // in-memory layers
    8245            4 :                 // delta layers
    8246            4 :                 vec![
    8247            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8248            4 :                         Lsn(0x10)..Lsn(0x20),
    8249            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8250            4 :                     ),
    8251            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8252            4 :                         Lsn(0x20)..Lsn(0x30),
    8253            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8254            4 :                     ),
    8255            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8256            4 :                         Lsn(0x20)..Lsn(0x30),
    8257            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8258            4 :                     ),
    8259            4 :                 ],
    8260            4 :                 // image layers
    8261            4 :                 vec![
    8262            4 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8263            4 :                     (
    8264            4 :                         Lsn(0x30),
    8265            4 :                         vec![
    8266            4 :                             (key0, test_img("metadata key 0")),
    8267            4 :                             (key3, test_img("metadata key 3")),
    8268            4 :                         ],
    8269            4 :                     ),
    8270            4 :                 ],
    8271            4 :                 Lsn(0x30),
    8272            4 :             )
    8273            4 :             .await?;
    8274            4 : 
    8275            4 :         let lsn = Lsn(0x30);
    8276            4 :         let old_lsn = Lsn(0x20);
    8277            4 : 
    8278            4 :         assert_eq!(
    8279            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8280            4 :             Some(test_img("metadata key 0"))
    8281            4 :         );
    8282            4 :         assert_eq!(
    8283            4 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8284            4 :             None,
    8285            4 :         );
    8286            4 :         assert_eq!(
    8287            4 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8288            4 :             None,
    8289            4 :         );
    8290            4 :         assert_eq!(
    8291            4 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8292            4 :             Some(Bytes::new()),
    8293            4 :         );
    8294            4 :         assert_eq!(
    8295            4 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8296            4 :             Some(Bytes::new()),
    8297            4 :         );
    8298            4 :         assert_eq!(
    8299            4 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8300            4 :             Some(test_img("metadata key 3"))
    8301            4 :         );
    8302            4 : 
    8303            4 :         Ok(())
    8304            4 :     }
    8305              : 
    8306              :     #[tokio::test]
    8307            4 :     async fn test_metadata_tombstone_image_creation() {
    8308            4 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8309            4 :             .await
    8310            4 :             .unwrap();
    8311            4 :         let (tenant, ctx) = harness.load().await;
    8312            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8313            4 : 
    8314            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8315            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8316            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8317            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8318            4 : 
    8319            4 :         let tline = tenant
    8320            4 :             .create_test_timeline_with_layers(
    8321            4 :                 TIMELINE_ID,
    8322            4 :                 Lsn(0x10),
    8323            4 :                 DEFAULT_PG_VERSION,
    8324            4 :                 &ctx,
    8325            4 :                 Vec::new(), // in-memory layers
    8326            4 :                 // delta layers
    8327            4 :                 vec![
    8328            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8329            4 :                         Lsn(0x10)..Lsn(0x20),
    8330            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8331            4 :                     ),
    8332            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8333            4 :                         Lsn(0x20)..Lsn(0x30),
    8334            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8335            4 :                     ),
    8336            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8337            4 :                         Lsn(0x20)..Lsn(0x30),
    8338            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8339            4 :                     ),
    8340            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8341            4 :                         Lsn(0x30)..Lsn(0x40),
    8342            4 :                         vec![
    8343            4 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8344            4 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8345            4 :                         ],
    8346            4 :                     ),
    8347            4 :                 ],
    8348            4 :                 // image layers
    8349            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8350            4 :                 Lsn(0x40),
    8351            4 :             )
    8352            4 :             .await
    8353            4 :             .unwrap();
    8354            4 : 
    8355            4 :         let cancel = CancellationToken::new();
    8356            4 : 
    8357            4 :         tline
    8358            4 :             .compact(
    8359            4 :                 &cancel,
    8360            4 :                 {
    8361            4 :                     let mut flags = EnumSet::new();
    8362            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8363            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8364            4 :                     flags
    8365            4 :                 },
    8366            4 :                 &ctx,
    8367            4 :             )
    8368            4 :             .await
    8369            4 :             .unwrap();
    8370            4 : 
    8371            4 :         // Image layers are created at last_record_lsn
    8372            4 :         let images = tline
    8373            4 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8374            4 :             .await
    8375            4 :             .unwrap()
    8376            4 :             .into_iter()
    8377           36 :             .filter(|(k, _)| k.is_metadata_key())
    8378            4 :             .collect::<Vec<_>>();
    8379            4 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8380            4 :     }
    8381              : 
    8382              :     #[tokio::test]
    8383            4 :     async fn test_metadata_tombstone_empty_image_creation() {
    8384            4 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8385            4 :             .await
    8386            4 :             .unwrap();
    8387            4 :         let (tenant, ctx) = harness.load().await;
    8388            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8389            4 : 
    8390            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8391            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8392            4 : 
    8393            4 :         let tline = tenant
    8394            4 :             .create_test_timeline_with_layers(
    8395            4 :                 TIMELINE_ID,
    8396            4 :                 Lsn(0x10),
    8397            4 :                 DEFAULT_PG_VERSION,
    8398            4 :                 &ctx,
    8399            4 :                 Vec::new(), // in-memory layers
    8400            4 :                 // delta layers
    8401            4 :                 vec![
    8402            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8403            4 :                         Lsn(0x10)..Lsn(0x20),
    8404            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8405            4 :                     ),
    8406            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8407            4 :                         Lsn(0x20)..Lsn(0x30),
    8408            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8409            4 :                     ),
    8410            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8411            4 :                         Lsn(0x20)..Lsn(0x30),
    8412            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8413            4 :                     ),
    8414            4 :                 ],
    8415            4 :                 // image layers
    8416            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8417            4 :                 Lsn(0x30),
    8418            4 :             )
    8419            4 :             .await
    8420            4 :             .unwrap();
    8421            4 : 
    8422            4 :         let cancel = CancellationToken::new();
    8423            4 : 
    8424            4 :         tline
    8425            4 :             .compact(
    8426            4 :                 &cancel,
    8427            4 :                 {
    8428            4 :                     let mut flags = EnumSet::new();
    8429            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8430            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8431            4 :                     flags
    8432            4 :                 },
    8433            4 :                 &ctx,
    8434            4 :             )
    8435            4 :             .await
    8436            4 :             .unwrap();
    8437            4 : 
    8438            4 :         // Image layers are created at last_record_lsn
    8439            4 :         let images = tline
    8440            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8441            4 :             .await
    8442            4 :             .unwrap()
    8443            4 :             .into_iter()
    8444           28 :             .filter(|(k, _)| k.is_metadata_key())
    8445            4 :             .collect::<Vec<_>>();
    8446            4 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8447            4 :     }
    8448              : 
    8449              :     #[tokio::test]
    8450            4 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8451            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8452            4 :         let (tenant, ctx) = harness.load().await;
    8453            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8454            4 : 
    8455          204 :         fn get_key(id: u32) -> Key {
    8456          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8457          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8458          204 :             key.field6 = id;
    8459          204 :             key
    8460          204 :         }
    8461            4 : 
    8462            4 :         // We create
    8463            4 :         // - one bottom-most image layer,
    8464            4 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8465            4 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8466            4 :         // - a delta layer D3 above the horizon.
    8467            4 :         //
    8468            4 :         //                             | D3 |
    8469            4 :         //  | D1 |
    8470            4 :         // -|    |-- gc horizon -----------------
    8471            4 :         //  |    |                | D2 |
    8472            4 :         // --------- img layer ------------------
    8473            4 :         //
    8474            4 :         // What we should expact from this compaction is:
    8475            4 :         //                             | D3 |
    8476            4 :         //  | Part of D1 |
    8477            4 :         // --------- img layer with D1+D2 at GC horizon------------------
    8478            4 : 
    8479            4 :         // img layer at 0x10
    8480            4 :         let img_layer = (0..10)
    8481           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8482            4 :             .collect_vec();
    8483            4 : 
    8484            4 :         let delta1 = vec![
    8485            4 :             (
    8486            4 :                 get_key(1),
    8487            4 :                 Lsn(0x20),
    8488            4 :                 Value::Image(Bytes::from("value 1@0x20")),
    8489            4 :             ),
    8490            4 :             (
    8491            4 :                 get_key(2),
    8492            4 :                 Lsn(0x30),
    8493            4 :                 Value::Image(Bytes::from("value 2@0x30")),
    8494            4 :             ),
    8495            4 :             (
    8496            4 :                 get_key(3),
    8497            4 :                 Lsn(0x40),
    8498            4 :                 Value::Image(Bytes::from("value 3@0x40")),
    8499            4 :             ),
    8500            4 :         ];
    8501            4 :         let delta2 = vec![
    8502            4 :             (
    8503            4 :                 get_key(5),
    8504            4 :                 Lsn(0x20),
    8505            4 :                 Value::Image(Bytes::from("value 5@0x20")),
    8506            4 :             ),
    8507            4 :             (
    8508            4 :                 get_key(6),
    8509            4 :                 Lsn(0x20),
    8510            4 :                 Value::Image(Bytes::from("value 6@0x20")),
    8511            4 :             ),
    8512            4 :         ];
    8513            4 :         let delta3 = vec![
    8514            4 :             (
    8515            4 :                 get_key(8),
    8516            4 :                 Lsn(0x48),
    8517            4 :                 Value::Image(Bytes::from("value 8@0x48")),
    8518            4 :             ),
    8519            4 :             (
    8520            4 :                 get_key(9),
    8521            4 :                 Lsn(0x48),
    8522            4 :                 Value::Image(Bytes::from("value 9@0x48")),
    8523            4 :             ),
    8524            4 :         ];
    8525            4 : 
    8526            4 :         let tline = tenant
    8527            4 :             .create_test_timeline_with_layers(
    8528            4 :                 TIMELINE_ID,
    8529            4 :                 Lsn(0x10),
    8530            4 :                 DEFAULT_PG_VERSION,
    8531            4 :                 &ctx,
    8532            4 :                 Vec::new(), // in-memory layers
    8533            4 :                 vec![
    8534            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8535            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8536            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8537            4 :                 ], // delta layers
    8538            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8539            4 :                 Lsn(0x50),
    8540            4 :             )
    8541            4 :             .await?;
    8542            4 :         {
    8543            4 :             tline
    8544            4 :                 .applied_gc_cutoff_lsn
    8545            4 :                 .lock_for_write()
    8546            4 :                 .store_and_unlock(Lsn(0x30))
    8547            4 :                 .wait()
    8548            4 :                 .await;
    8549            4 :             // Update GC info
    8550            4 :             let mut guard = tline.gc_info.write().unwrap();
    8551            4 :             guard.cutoffs.time = Lsn(0x30);
    8552            4 :             guard.cutoffs.space = Lsn(0x30);
    8553            4 :         }
    8554            4 : 
    8555            4 :         let expected_result = [
    8556            4 :             Bytes::from_static(b"value 0@0x10"),
    8557            4 :             Bytes::from_static(b"value 1@0x20"),
    8558            4 :             Bytes::from_static(b"value 2@0x30"),
    8559            4 :             Bytes::from_static(b"value 3@0x40"),
    8560            4 :             Bytes::from_static(b"value 4@0x10"),
    8561            4 :             Bytes::from_static(b"value 5@0x20"),
    8562            4 :             Bytes::from_static(b"value 6@0x20"),
    8563            4 :             Bytes::from_static(b"value 7@0x10"),
    8564            4 :             Bytes::from_static(b"value 8@0x48"),
    8565            4 :             Bytes::from_static(b"value 9@0x48"),
    8566            4 :         ];
    8567            4 : 
    8568           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8569           40 :             assert_eq!(
    8570           40 :                 tline
    8571           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8572           40 :                     .await
    8573           40 :                     .unwrap(),
    8574            4 :                 expected
    8575            4 :             );
    8576            4 :         }
    8577            4 : 
    8578            4 :         let cancel = CancellationToken::new();
    8579            4 :         tline
    8580            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8581            4 :             .await
    8582            4 :             .unwrap();
    8583            4 : 
    8584           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8585           40 :             assert_eq!(
    8586           40 :                 tline
    8587           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8588           40 :                     .await
    8589           40 :                     .unwrap(),
    8590            4 :                 expected
    8591            4 :             );
    8592            4 :         }
    8593            4 : 
    8594            4 :         // Check if the image layer at the GC horizon contains exactly what we want
    8595            4 :         let image_at_gc_horizon = tline
    8596            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8597            4 :             .await
    8598            4 :             .unwrap()
    8599            4 :             .into_iter()
    8600           68 :             .filter(|(k, _)| k.is_metadata_key())
    8601            4 :             .collect::<Vec<_>>();
    8602            4 : 
    8603            4 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8604            4 :         let expected_result = [
    8605            4 :             Bytes::from_static(b"value 0@0x10"),
    8606            4 :             Bytes::from_static(b"value 1@0x20"),
    8607            4 :             Bytes::from_static(b"value 2@0x30"),
    8608            4 :             Bytes::from_static(b"value 3@0x10"),
    8609            4 :             Bytes::from_static(b"value 4@0x10"),
    8610            4 :             Bytes::from_static(b"value 5@0x20"),
    8611            4 :             Bytes::from_static(b"value 6@0x20"),
    8612            4 :             Bytes::from_static(b"value 7@0x10"),
    8613            4 :             Bytes::from_static(b"value 8@0x10"),
    8614            4 :             Bytes::from_static(b"value 9@0x10"),
    8615            4 :         ];
    8616           44 :         for idx in 0..10 {
    8617           40 :             assert_eq!(
    8618           40 :                 image_at_gc_horizon[idx],
    8619           40 :                 (get_key(idx as u32), expected_result[idx].clone())
    8620           40 :             );
    8621            4 :         }
    8622            4 : 
    8623            4 :         // Check if old layers are removed / new layers have the expected LSN
    8624            4 :         let all_layers = inspect_and_sort(&tline, None).await;
    8625            4 :         assert_eq!(
    8626            4 :             all_layers,
    8627            4 :             vec![
    8628            4 :                 // Image layer at GC horizon
    8629            4 :                 PersistentLayerKey {
    8630            4 :                     key_range: Key::MIN..Key::MAX,
    8631            4 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8632            4 :                     is_delta: false
    8633            4 :                 },
    8634            4 :                 // The delta layer below the horizon
    8635            4 :                 PersistentLayerKey {
    8636            4 :                     key_range: get_key(3)..get_key(4),
    8637            4 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8638            4 :                     is_delta: true
    8639            4 :                 },
    8640            4 :                 // The delta3 layer that should not be picked for the compaction
    8641            4 :                 PersistentLayerKey {
    8642            4 :                     key_range: get_key(8)..get_key(10),
    8643            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8644            4 :                     is_delta: true
    8645            4 :                 }
    8646            4 :             ]
    8647            4 :         );
    8648            4 : 
    8649            4 :         // increase GC horizon and compact again
    8650            4 :         {
    8651            4 :             tline
    8652            4 :                 .applied_gc_cutoff_lsn
    8653            4 :                 .lock_for_write()
    8654            4 :                 .store_and_unlock(Lsn(0x40))
    8655            4 :                 .wait()
    8656            4 :                 .await;
    8657            4 :             // Update GC info
    8658            4 :             let mut guard = tline.gc_info.write().unwrap();
    8659            4 :             guard.cutoffs.time = Lsn(0x40);
    8660            4 :             guard.cutoffs.space = Lsn(0x40);
    8661            4 :         }
    8662            4 :         tline
    8663            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8664            4 :             .await
    8665            4 :             .unwrap();
    8666            4 : 
    8667            4 :         Ok(())
    8668            4 :     }
    8669              : 
    8670              :     #[cfg(feature = "testing")]
    8671              :     #[tokio::test]
    8672            4 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8673            4 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8674            4 :         let (tenant, ctx) = harness.load().await;
    8675            4 : 
    8676           48 :         fn get_key(id: u32) -> Key {
    8677           48 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8678           48 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8679           48 :             key.field6 = id;
    8680           48 :             key
    8681           48 :         }
    8682            4 : 
    8683            4 :         let delta1 = vec![
    8684            4 :             (
    8685            4 :                 get_key(1),
    8686            4 :                 Lsn(0x20),
    8687            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8688            4 :             ),
    8689            4 :             (
    8690            4 :                 get_key(1),
    8691            4 :                 Lsn(0x30),
    8692            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8693            4 :             ),
    8694            4 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8695            4 :             (
    8696            4 :                 get_key(2),
    8697            4 :                 Lsn(0x20),
    8698            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8699            4 :             ),
    8700            4 :             (
    8701            4 :                 get_key(2),
    8702            4 :                 Lsn(0x30),
    8703            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8704            4 :             ),
    8705            4 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8706            4 :             (
    8707            4 :                 get_key(3),
    8708            4 :                 Lsn(0x20),
    8709            4 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8710            4 :             ),
    8711            4 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8712            4 :             (
    8713            4 :                 get_key(4),
    8714            4 :                 Lsn(0x20),
    8715            4 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8716            4 :             ),
    8717            4 :         ];
    8718            4 :         let image1 = vec![(get_key(1), "0x10".into())];
    8719            4 : 
    8720            4 :         let tline = tenant
    8721            4 :             .create_test_timeline_with_layers(
    8722            4 :                 TIMELINE_ID,
    8723            4 :                 Lsn(0x10),
    8724            4 :                 DEFAULT_PG_VERSION,
    8725            4 :                 &ctx,
    8726            4 :                 Vec::new(), // in-memory layers
    8727            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8728            4 :                     Lsn(0x10)..Lsn(0x40),
    8729            4 :                     delta1,
    8730            4 :                 )], // delta layers
    8731            4 :                 vec![(Lsn(0x10), image1)], // image layers
    8732            4 :                 Lsn(0x50),
    8733            4 :             )
    8734            4 :             .await?;
    8735            4 : 
    8736            4 :         assert_eq!(
    8737            4 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8738            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8739            4 :         );
    8740            4 :         assert_eq!(
    8741            4 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8742            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8743            4 :         );
    8744            4 : 
    8745            4 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8746            4 : 
    8747            4 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8748            4 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8749            4 : 
    8750            4 :         Ok(())
    8751            4 :     }
    8752              : 
    8753              :     #[tokio::test(start_paused = true)]
    8754            4 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8755            4 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8756            4 :             .await
    8757            4 :             .unwrap()
    8758            4 :             .load()
    8759            4 :             .await;
    8760            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8761            4 :         // initial transition into AttachedSingle.
    8762            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8763            4 :         tokio::time::resume();
    8764            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8765            4 : 
    8766            4 :         let end_lsn = Lsn(0x100);
    8767            4 :         let image_layers = (0x20..=0x90)
    8768            4 :             .step_by(0x10)
    8769           32 :             .map(|n| {
    8770           32 :                 (
    8771           32 :                     Lsn(n),
    8772           32 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8773           32 :                 )
    8774           32 :             })
    8775            4 :             .collect();
    8776            4 : 
    8777            4 :         let timeline = tenant
    8778            4 :             .create_test_timeline_with_layers(
    8779            4 :                 TIMELINE_ID,
    8780            4 :                 Lsn(0x10),
    8781            4 :                 DEFAULT_PG_VERSION,
    8782            4 :                 &ctx,
    8783            4 :                 Vec::new(), // in-memory layers
    8784            4 :                 Vec::new(),
    8785            4 :                 image_layers,
    8786            4 :                 end_lsn,
    8787            4 :             )
    8788            4 :             .await?;
    8789            4 : 
    8790            4 :         let leased_lsns = [0x30, 0x50, 0x70];
    8791            4 :         let mut leases = Vec::new();
    8792           12 :         leased_lsns.iter().for_each(|n| {
    8793           12 :             leases.push(
    8794           12 :                 timeline
    8795           12 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8796           12 :                     .expect("lease request should succeed"),
    8797           12 :             );
    8798           12 :         });
    8799            4 : 
    8800            4 :         let updated_lease_0 = timeline
    8801            4 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8802            4 :             .expect("lease renewal should succeed");
    8803            4 :         assert_eq!(
    8804            4 :             updated_lease_0.valid_until, leases[0].valid_until,
    8805            4 :             " Renewing with shorter lease should not change the lease."
    8806            4 :         );
    8807            4 : 
    8808            4 :         let updated_lease_1 = timeline
    8809            4 :             .renew_lsn_lease(
    8810            4 :                 Lsn(leased_lsns[1]),
    8811            4 :                 timeline.get_lsn_lease_length() * 2,
    8812            4 :                 &ctx,
    8813            4 :             )
    8814            4 :             .expect("lease renewal should succeed");
    8815            4 :         assert!(
    8816            4 :             updated_lease_1.valid_until > leases[1].valid_until,
    8817            4 :             "Renewing with a long lease should renew lease with later expiration time."
    8818            4 :         );
    8819            4 : 
    8820            4 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8821            4 :         info!(
    8822            4 :             "applied_gc_cutoff_lsn: {}",
    8823            0 :             *timeline.get_applied_gc_cutoff_lsn()
    8824            4 :         );
    8825            4 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8826            4 : 
    8827            4 :         let res = tenant
    8828            4 :             .gc_iteration(
    8829            4 :                 Some(TIMELINE_ID),
    8830            4 :                 0,
    8831            4 :                 Duration::ZERO,
    8832            4 :                 &CancellationToken::new(),
    8833            4 :                 &ctx,
    8834            4 :             )
    8835            4 :             .await
    8836            4 :             .unwrap();
    8837            4 : 
    8838            4 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8839            4 :         // 0/10: initdb layer
    8840            4 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8841            4 :         assert_eq!(res.layers_needed_by_leases, 7);
    8842            4 :         // Keeping 0/90 b/c it is the latest layer.
    8843            4 :         assert_eq!(res.layers_not_updated, 1);
    8844            4 :         // Removed 0/80.
    8845            4 :         assert_eq!(res.layers_removed, 1);
    8846            4 : 
    8847            4 :         // Make lease on a already GC-ed LSN.
    8848            4 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8849            4 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    8850            4 :         timeline
    8851            4 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8852            4 :             .expect_err("lease request on GC-ed LSN should fail");
    8853            4 : 
    8854            4 :         // Should still be able to renew a currently valid lease
    8855            4 :         // Assumption: original lease to is still valid for 0/50.
    8856            4 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8857            4 :         timeline
    8858            4 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8859            4 :             .expect("lease renewal with validation should succeed");
    8860            4 : 
    8861            4 :         Ok(())
    8862            4 :     }
    8863              : 
    8864              :     #[cfg(feature = "testing")]
    8865              :     #[tokio::test]
    8866            4 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8867            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8868            4 :             "test_simple_bottom_most_compaction_deltas_1",
    8869            4 :             false,
    8870            4 :         )
    8871            4 :         .await
    8872            4 :     }
    8873              : 
    8874              :     #[cfg(feature = "testing")]
    8875              :     #[tokio::test]
    8876            4 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8877            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8878            4 :             "test_simple_bottom_most_compaction_deltas_2",
    8879            4 :             true,
    8880            4 :         )
    8881            4 :         .await
    8882            4 :     }
    8883              : 
    8884              :     #[cfg(feature = "testing")]
    8885            8 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8886            8 :         test_name: &'static str,
    8887            8 :         use_delta_bottom_layer: bool,
    8888            8 :     ) -> anyhow::Result<()> {
    8889            8 :         let harness = TenantHarness::create(test_name).await?;
    8890            8 :         let (tenant, ctx) = harness.load().await;
    8891              : 
    8892          552 :         fn get_key(id: u32) -> Key {
    8893          552 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8894          552 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8895          552 :             key.field6 = id;
    8896          552 :             key
    8897          552 :         }
    8898              : 
    8899              :         // We create
    8900              :         // - one bottom-most image layer,
    8901              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8902              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8903              :         // - a delta layer D3 above the horizon.
    8904              :         //
    8905              :         //                             | D3 |
    8906              :         //  | D1 |
    8907              :         // -|    |-- gc horizon -----------------
    8908              :         //  |    |                | D2 |
    8909              :         // --------- img layer ------------------
    8910              :         //
    8911              :         // What we should expact from this compaction is:
    8912              :         //                             | D3 |
    8913              :         //  | Part of D1 |
    8914              :         // --------- img layer with D1+D2 at GC horizon------------------
    8915              : 
    8916              :         // img layer at 0x10
    8917            8 :         let img_layer = (0..10)
    8918           80 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8919            8 :             .collect_vec();
    8920            8 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8921            8 :         let delta4 = (0..10)
    8922           80 :             .map(|id| {
    8923           80 :                 (
    8924           80 :                     get_key(id),
    8925           80 :                     Lsn(0x08),
    8926           80 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8927           80 :                 )
    8928           80 :             })
    8929            8 :             .collect_vec();
    8930            8 : 
    8931            8 :         let delta1 = vec![
    8932            8 :             (
    8933            8 :                 get_key(1),
    8934            8 :                 Lsn(0x20),
    8935            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8936            8 :             ),
    8937            8 :             (
    8938            8 :                 get_key(2),
    8939            8 :                 Lsn(0x30),
    8940            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8941            8 :             ),
    8942            8 :             (
    8943            8 :                 get_key(3),
    8944            8 :                 Lsn(0x28),
    8945            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8946            8 :             ),
    8947            8 :             (
    8948            8 :                 get_key(3),
    8949            8 :                 Lsn(0x30),
    8950            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8951            8 :             ),
    8952            8 :             (
    8953            8 :                 get_key(3),
    8954            8 :                 Lsn(0x40),
    8955            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8956            8 :             ),
    8957            8 :         ];
    8958            8 :         let delta2 = vec![
    8959            8 :             (
    8960            8 :                 get_key(5),
    8961            8 :                 Lsn(0x20),
    8962            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8963            8 :             ),
    8964            8 :             (
    8965            8 :                 get_key(6),
    8966            8 :                 Lsn(0x20),
    8967            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8968            8 :             ),
    8969            8 :         ];
    8970            8 :         let delta3 = vec![
    8971            8 :             (
    8972            8 :                 get_key(8),
    8973            8 :                 Lsn(0x48),
    8974            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8975            8 :             ),
    8976            8 :             (
    8977            8 :                 get_key(9),
    8978            8 :                 Lsn(0x48),
    8979            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8980            8 :             ),
    8981            8 :         ];
    8982              : 
    8983            8 :         let tline = if use_delta_bottom_layer {
    8984            4 :             tenant
    8985            4 :                 .create_test_timeline_with_layers(
    8986            4 :                     TIMELINE_ID,
    8987            4 :                     Lsn(0x08),
    8988            4 :                     DEFAULT_PG_VERSION,
    8989            4 :                     &ctx,
    8990            4 :                     Vec::new(), // in-memory layers
    8991            4 :                     vec![
    8992            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8993            4 :                             Lsn(0x08)..Lsn(0x10),
    8994            4 :                             delta4,
    8995            4 :                         ),
    8996            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8997            4 :                             Lsn(0x20)..Lsn(0x48),
    8998            4 :                             delta1,
    8999            4 :                         ),
    9000            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9001            4 :                             Lsn(0x20)..Lsn(0x48),
    9002            4 :                             delta2,
    9003            4 :                         ),
    9004            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9005            4 :                             Lsn(0x48)..Lsn(0x50),
    9006            4 :                             delta3,
    9007            4 :                         ),
    9008            4 :                     ], // delta layers
    9009            4 :                     vec![],     // image layers
    9010            4 :                     Lsn(0x50),
    9011            4 :                 )
    9012            4 :                 .await?
    9013              :         } else {
    9014            4 :             tenant
    9015            4 :                 .create_test_timeline_with_layers(
    9016            4 :                     TIMELINE_ID,
    9017            4 :                     Lsn(0x10),
    9018            4 :                     DEFAULT_PG_VERSION,
    9019            4 :                     &ctx,
    9020            4 :                     Vec::new(), // in-memory layers
    9021            4 :                     vec![
    9022            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9023            4 :                             Lsn(0x10)..Lsn(0x48),
    9024            4 :                             delta1,
    9025            4 :                         ),
    9026            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9027            4 :                             Lsn(0x10)..Lsn(0x48),
    9028            4 :                             delta2,
    9029            4 :                         ),
    9030            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9031            4 :                             Lsn(0x48)..Lsn(0x50),
    9032            4 :                             delta3,
    9033            4 :                         ),
    9034            4 :                     ], // delta layers
    9035            4 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9036            4 :                     Lsn(0x50),
    9037            4 :                 )
    9038            4 :                 .await?
    9039              :         };
    9040              :         {
    9041            8 :             tline
    9042            8 :                 .applied_gc_cutoff_lsn
    9043            8 :                 .lock_for_write()
    9044            8 :                 .store_and_unlock(Lsn(0x30))
    9045            8 :                 .wait()
    9046            8 :                 .await;
    9047              :             // Update GC info
    9048            8 :             let mut guard = tline.gc_info.write().unwrap();
    9049            8 :             *guard = GcInfo {
    9050            8 :                 retain_lsns: vec![],
    9051            8 :                 cutoffs: GcCutoffs {
    9052            8 :                     time: Lsn(0x30),
    9053            8 :                     space: Lsn(0x30),
    9054            8 :                 },
    9055            8 :                 leases: Default::default(),
    9056            8 :                 within_ancestor_pitr: false,
    9057            8 :             };
    9058            8 :         }
    9059            8 : 
    9060            8 :         let expected_result = [
    9061            8 :             Bytes::from_static(b"value 0@0x10"),
    9062            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9063            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9064            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9065            8 :             Bytes::from_static(b"value 4@0x10"),
    9066            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9067            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9068            8 :             Bytes::from_static(b"value 7@0x10"),
    9069            8 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9070            8 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9071            8 :         ];
    9072            8 : 
    9073            8 :         let expected_result_at_gc_horizon = [
    9074            8 :             Bytes::from_static(b"value 0@0x10"),
    9075            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9076            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9077            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9078            8 :             Bytes::from_static(b"value 4@0x10"),
    9079            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9080            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9081            8 :             Bytes::from_static(b"value 7@0x10"),
    9082            8 :             Bytes::from_static(b"value 8@0x10"),
    9083            8 :             Bytes::from_static(b"value 9@0x10"),
    9084            8 :         ];
    9085              : 
    9086           88 :         for idx in 0..10 {
    9087           80 :             assert_eq!(
    9088           80 :                 tline
    9089           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9090           80 :                     .await
    9091           80 :                     .unwrap(),
    9092           80 :                 &expected_result[idx]
    9093              :             );
    9094           80 :             assert_eq!(
    9095           80 :                 tline
    9096           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9097           80 :                     .await
    9098           80 :                     .unwrap(),
    9099           80 :                 &expected_result_at_gc_horizon[idx]
    9100              :             );
    9101              :         }
    9102              : 
    9103            8 :         let cancel = CancellationToken::new();
    9104            8 :         tline
    9105            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9106            8 :             .await
    9107            8 :             .unwrap();
    9108              : 
    9109           88 :         for idx in 0..10 {
    9110           80 :             assert_eq!(
    9111           80 :                 tline
    9112           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9113           80 :                     .await
    9114           80 :                     .unwrap(),
    9115           80 :                 &expected_result[idx]
    9116              :             );
    9117           80 :             assert_eq!(
    9118           80 :                 tline
    9119           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9120           80 :                     .await
    9121           80 :                     .unwrap(),
    9122           80 :                 &expected_result_at_gc_horizon[idx]
    9123              :             );
    9124              :         }
    9125              : 
    9126              :         // increase GC horizon and compact again
    9127              :         {
    9128            8 :             tline
    9129            8 :                 .applied_gc_cutoff_lsn
    9130            8 :                 .lock_for_write()
    9131            8 :                 .store_and_unlock(Lsn(0x40))
    9132            8 :                 .wait()
    9133            8 :                 .await;
    9134              :             // Update GC info
    9135            8 :             let mut guard = tline.gc_info.write().unwrap();
    9136            8 :             guard.cutoffs.time = Lsn(0x40);
    9137            8 :             guard.cutoffs.space = Lsn(0x40);
    9138            8 :         }
    9139            8 :         tline
    9140            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9141            8 :             .await
    9142            8 :             .unwrap();
    9143            8 : 
    9144            8 :         Ok(())
    9145            8 :     }
    9146              : 
    9147              :     #[cfg(feature = "testing")]
    9148              :     #[tokio::test]
    9149            4 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9150            4 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9151            4 :         let (tenant, ctx) = harness.load().await;
    9152            4 :         let tline = tenant
    9153            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9154            4 :             .await?;
    9155            4 :         tline.force_advance_lsn(Lsn(0x70));
    9156            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9157            4 :         let history = vec![
    9158            4 :             (
    9159            4 :                 key,
    9160            4 :                 Lsn(0x10),
    9161            4 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9162            4 :             ),
    9163            4 :             (
    9164            4 :                 key,
    9165            4 :                 Lsn(0x20),
    9166            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9167            4 :             ),
    9168            4 :             (
    9169            4 :                 key,
    9170            4 :                 Lsn(0x30),
    9171            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9172            4 :             ),
    9173            4 :             (
    9174            4 :                 key,
    9175            4 :                 Lsn(0x40),
    9176            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9177            4 :             ),
    9178            4 :             (
    9179            4 :                 key,
    9180            4 :                 Lsn(0x50),
    9181            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9182            4 :             ),
    9183            4 :             (
    9184            4 :                 key,
    9185            4 :                 Lsn(0x60),
    9186            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9187            4 :             ),
    9188            4 :             (
    9189            4 :                 key,
    9190            4 :                 Lsn(0x70),
    9191            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9192            4 :             ),
    9193            4 :             (
    9194            4 :                 key,
    9195            4 :                 Lsn(0x80),
    9196            4 :                 Value::Image(Bytes::copy_from_slice(
    9197            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9198            4 :                 )),
    9199            4 :             ),
    9200            4 :             (
    9201            4 :                 key,
    9202            4 :                 Lsn(0x90),
    9203            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9204            4 :             ),
    9205            4 :         ];
    9206            4 :         let res = tline
    9207            4 :             .generate_key_retention(
    9208            4 :                 key,
    9209            4 :                 &history,
    9210            4 :                 Lsn(0x60),
    9211            4 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9212            4 :                 3,
    9213            4 :                 None,
    9214            4 :             )
    9215            4 :             .await
    9216            4 :             .unwrap();
    9217            4 :         let expected_res = KeyHistoryRetention {
    9218            4 :             below_horizon: vec![
    9219            4 :                 (
    9220            4 :                     Lsn(0x20),
    9221            4 :                     KeyLogAtLsn(vec![(
    9222            4 :                         Lsn(0x20),
    9223            4 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9224            4 :                     )]),
    9225            4 :                 ),
    9226            4 :                 (
    9227            4 :                     Lsn(0x40),
    9228            4 :                     KeyLogAtLsn(vec![
    9229            4 :                         (
    9230            4 :                             Lsn(0x30),
    9231            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9232            4 :                         ),
    9233            4 :                         (
    9234            4 :                             Lsn(0x40),
    9235            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9236            4 :                         ),
    9237            4 :                     ]),
    9238            4 :                 ),
    9239            4 :                 (
    9240            4 :                     Lsn(0x50),
    9241            4 :                     KeyLogAtLsn(vec![(
    9242            4 :                         Lsn(0x50),
    9243            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9244            4 :                     )]),
    9245            4 :                 ),
    9246            4 :                 (
    9247            4 :                     Lsn(0x60),
    9248            4 :                     KeyLogAtLsn(vec![(
    9249            4 :                         Lsn(0x60),
    9250            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9251            4 :                     )]),
    9252            4 :                 ),
    9253            4 :             ],
    9254            4 :             above_horizon: KeyLogAtLsn(vec![
    9255            4 :                 (
    9256            4 :                     Lsn(0x70),
    9257            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9258            4 :                 ),
    9259            4 :                 (
    9260            4 :                     Lsn(0x80),
    9261            4 :                     Value::Image(Bytes::copy_from_slice(
    9262            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9263            4 :                     )),
    9264            4 :                 ),
    9265            4 :                 (
    9266            4 :                     Lsn(0x90),
    9267            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9268            4 :                 ),
    9269            4 :             ]),
    9270            4 :         };
    9271            4 :         assert_eq!(res, expected_res);
    9272            4 : 
    9273            4 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9274            4 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9275            4 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9276            4 :         // For example, we have
    9277            4 :         // ```plain
    9278            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9279            4 :         // ```
    9280            4 :         // Now the GC horizon moves up, and we have
    9281            4 :         // ```plain
    9282            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9283            4 :         // ```
    9284            4 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9285            4 :         // We will end up with
    9286            4 :         // ```plain
    9287            4 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9288            4 :         // ```
    9289            4 :         // Now we run the GC-compaction, and this key does not have a full history.
    9290            4 :         // We should be able to handle this partial history and drop everything before the
    9291            4 :         // gc_horizon image.
    9292            4 : 
    9293            4 :         let history = vec![
    9294            4 :             (
    9295            4 :                 key,
    9296            4 :                 Lsn(0x20),
    9297            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9298            4 :             ),
    9299            4 :             (
    9300            4 :                 key,
    9301            4 :                 Lsn(0x30),
    9302            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9303            4 :             ),
    9304            4 :             (
    9305            4 :                 key,
    9306            4 :                 Lsn(0x40),
    9307            4 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9308            4 :             ),
    9309            4 :             (
    9310            4 :                 key,
    9311            4 :                 Lsn(0x50),
    9312            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9313            4 :             ),
    9314            4 :             (
    9315            4 :                 key,
    9316            4 :                 Lsn(0x60),
    9317            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9318            4 :             ),
    9319            4 :             (
    9320            4 :                 key,
    9321            4 :                 Lsn(0x70),
    9322            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9323            4 :             ),
    9324            4 :             (
    9325            4 :                 key,
    9326            4 :                 Lsn(0x80),
    9327            4 :                 Value::Image(Bytes::copy_from_slice(
    9328            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9329            4 :                 )),
    9330            4 :             ),
    9331            4 :             (
    9332            4 :                 key,
    9333            4 :                 Lsn(0x90),
    9334            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9335            4 :             ),
    9336            4 :         ];
    9337            4 :         let res = tline
    9338            4 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    9339            4 :             .await
    9340            4 :             .unwrap();
    9341            4 :         let expected_res = KeyHistoryRetention {
    9342            4 :             below_horizon: vec![
    9343            4 :                 (
    9344            4 :                     Lsn(0x40),
    9345            4 :                     KeyLogAtLsn(vec![(
    9346            4 :                         Lsn(0x40),
    9347            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9348            4 :                     )]),
    9349            4 :                 ),
    9350            4 :                 (
    9351            4 :                     Lsn(0x50),
    9352            4 :                     KeyLogAtLsn(vec![(
    9353            4 :                         Lsn(0x50),
    9354            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9355            4 :                     )]),
    9356            4 :                 ),
    9357            4 :                 (
    9358            4 :                     Lsn(0x60),
    9359            4 :                     KeyLogAtLsn(vec![(
    9360            4 :                         Lsn(0x60),
    9361            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9362            4 :                     )]),
    9363            4 :                 ),
    9364            4 :             ],
    9365            4 :             above_horizon: KeyLogAtLsn(vec![
    9366            4 :                 (
    9367            4 :                     Lsn(0x70),
    9368            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9369            4 :                 ),
    9370            4 :                 (
    9371            4 :                     Lsn(0x80),
    9372            4 :                     Value::Image(Bytes::copy_from_slice(
    9373            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9374            4 :                     )),
    9375            4 :                 ),
    9376            4 :                 (
    9377            4 :                     Lsn(0x90),
    9378            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9379            4 :                 ),
    9380            4 :             ]),
    9381            4 :         };
    9382            4 :         assert_eq!(res, expected_res);
    9383            4 : 
    9384            4 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9385            4 :         // the ancestor image in the test case.
    9386            4 : 
    9387            4 :         let history = vec![
    9388            4 :             (
    9389            4 :                 key,
    9390            4 :                 Lsn(0x20),
    9391            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9392            4 :             ),
    9393            4 :             (
    9394            4 :                 key,
    9395            4 :                 Lsn(0x30),
    9396            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9397            4 :             ),
    9398            4 :             (
    9399            4 :                 key,
    9400            4 :                 Lsn(0x40),
    9401            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9402            4 :             ),
    9403            4 :             (
    9404            4 :                 key,
    9405            4 :                 Lsn(0x70),
    9406            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9407            4 :             ),
    9408            4 :         ];
    9409            4 :         let res = tline
    9410            4 :             .generate_key_retention(
    9411            4 :                 key,
    9412            4 :                 &history,
    9413            4 :                 Lsn(0x60),
    9414            4 :                 &[],
    9415            4 :                 3,
    9416            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9417            4 :             )
    9418            4 :             .await
    9419            4 :             .unwrap();
    9420            4 :         let expected_res = KeyHistoryRetention {
    9421            4 :             below_horizon: vec![(
    9422            4 :                 Lsn(0x60),
    9423            4 :                 KeyLogAtLsn(vec![(
    9424            4 :                     Lsn(0x60),
    9425            4 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9426            4 :                 )]),
    9427            4 :             )],
    9428            4 :             above_horizon: KeyLogAtLsn(vec![(
    9429            4 :                 Lsn(0x70),
    9430            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9431            4 :             )]),
    9432            4 :         };
    9433            4 :         assert_eq!(res, expected_res);
    9434            4 : 
    9435            4 :         let history = vec![
    9436            4 :             (
    9437            4 :                 key,
    9438            4 :                 Lsn(0x20),
    9439            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9440            4 :             ),
    9441            4 :             (
    9442            4 :                 key,
    9443            4 :                 Lsn(0x40),
    9444            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9445            4 :             ),
    9446            4 :             (
    9447            4 :                 key,
    9448            4 :                 Lsn(0x60),
    9449            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9450            4 :             ),
    9451            4 :             (
    9452            4 :                 key,
    9453            4 :                 Lsn(0x70),
    9454            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9455            4 :             ),
    9456            4 :         ];
    9457            4 :         let res = tline
    9458            4 :             .generate_key_retention(
    9459            4 :                 key,
    9460            4 :                 &history,
    9461            4 :                 Lsn(0x60),
    9462            4 :                 &[Lsn(0x30)],
    9463            4 :                 3,
    9464            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9465            4 :             )
    9466            4 :             .await
    9467            4 :             .unwrap();
    9468            4 :         let expected_res = KeyHistoryRetention {
    9469            4 :             below_horizon: vec![
    9470            4 :                 (
    9471            4 :                     Lsn(0x30),
    9472            4 :                     KeyLogAtLsn(vec![(
    9473            4 :                         Lsn(0x20),
    9474            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9475            4 :                     )]),
    9476            4 :                 ),
    9477            4 :                 (
    9478            4 :                     Lsn(0x60),
    9479            4 :                     KeyLogAtLsn(vec![(
    9480            4 :                         Lsn(0x60),
    9481            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9482            4 :                     )]),
    9483            4 :                 ),
    9484            4 :             ],
    9485            4 :             above_horizon: KeyLogAtLsn(vec![(
    9486            4 :                 Lsn(0x70),
    9487            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9488            4 :             )]),
    9489            4 :         };
    9490            4 :         assert_eq!(res, expected_res);
    9491            4 : 
    9492            4 :         Ok(())
    9493            4 :     }
    9494              : 
    9495              :     #[cfg(feature = "testing")]
    9496              :     #[tokio::test]
    9497            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9498            4 :         let harness =
    9499            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9500            4 :         let (tenant, ctx) = harness.load().await;
    9501            4 : 
    9502         1036 :         fn get_key(id: u32) -> Key {
    9503         1036 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9504         1036 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9505         1036 :             key.field6 = id;
    9506         1036 :             key
    9507         1036 :         }
    9508            4 : 
    9509            4 :         let img_layer = (0..10)
    9510           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9511            4 :             .collect_vec();
    9512            4 : 
    9513            4 :         let delta1 = vec![
    9514            4 :             (
    9515            4 :                 get_key(1),
    9516            4 :                 Lsn(0x20),
    9517            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9518            4 :             ),
    9519            4 :             (
    9520            4 :                 get_key(2),
    9521            4 :                 Lsn(0x30),
    9522            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9523            4 :             ),
    9524            4 :             (
    9525            4 :                 get_key(3),
    9526            4 :                 Lsn(0x28),
    9527            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9528            4 :             ),
    9529            4 :             (
    9530            4 :                 get_key(3),
    9531            4 :                 Lsn(0x30),
    9532            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9533            4 :             ),
    9534            4 :             (
    9535            4 :                 get_key(3),
    9536            4 :                 Lsn(0x40),
    9537            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9538            4 :             ),
    9539            4 :         ];
    9540            4 :         let delta2 = vec![
    9541            4 :             (
    9542            4 :                 get_key(5),
    9543            4 :                 Lsn(0x20),
    9544            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9545            4 :             ),
    9546            4 :             (
    9547            4 :                 get_key(6),
    9548            4 :                 Lsn(0x20),
    9549            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9550            4 :             ),
    9551            4 :         ];
    9552            4 :         let delta3 = vec![
    9553            4 :             (
    9554            4 :                 get_key(8),
    9555            4 :                 Lsn(0x48),
    9556            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9557            4 :             ),
    9558            4 :             (
    9559            4 :                 get_key(9),
    9560            4 :                 Lsn(0x48),
    9561            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9562            4 :             ),
    9563            4 :         ];
    9564            4 : 
    9565            4 :         let tline = tenant
    9566            4 :             .create_test_timeline_with_layers(
    9567            4 :                 TIMELINE_ID,
    9568            4 :                 Lsn(0x10),
    9569            4 :                 DEFAULT_PG_VERSION,
    9570            4 :                 &ctx,
    9571            4 :                 Vec::new(), // in-memory layers
    9572            4 :                 vec![
    9573            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9574            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9575            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9576            4 :                 ], // delta layers
    9577            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9578            4 :                 Lsn(0x50),
    9579            4 :             )
    9580            4 :             .await?;
    9581            4 :         {
    9582            4 :             tline
    9583            4 :                 .applied_gc_cutoff_lsn
    9584            4 :                 .lock_for_write()
    9585            4 :                 .store_and_unlock(Lsn(0x30))
    9586            4 :                 .wait()
    9587            4 :                 .await;
    9588            4 :             // Update GC info
    9589            4 :             let mut guard = tline.gc_info.write().unwrap();
    9590            4 :             *guard = GcInfo {
    9591            4 :                 retain_lsns: vec![
    9592            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9593            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9594            4 :                 ],
    9595            4 :                 cutoffs: GcCutoffs {
    9596            4 :                     time: Lsn(0x30),
    9597            4 :                     space: Lsn(0x30),
    9598            4 :                 },
    9599            4 :                 leases: Default::default(),
    9600            4 :                 within_ancestor_pitr: false,
    9601            4 :             };
    9602            4 :         }
    9603            4 : 
    9604            4 :         let expected_result = [
    9605            4 :             Bytes::from_static(b"value 0@0x10"),
    9606            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9607            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9608            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9609            4 :             Bytes::from_static(b"value 4@0x10"),
    9610            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9611            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9612            4 :             Bytes::from_static(b"value 7@0x10"),
    9613            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9614            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9615            4 :         ];
    9616            4 : 
    9617            4 :         let expected_result_at_gc_horizon = [
    9618            4 :             Bytes::from_static(b"value 0@0x10"),
    9619            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9620            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9621            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9622            4 :             Bytes::from_static(b"value 4@0x10"),
    9623            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9624            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9625            4 :             Bytes::from_static(b"value 7@0x10"),
    9626            4 :             Bytes::from_static(b"value 8@0x10"),
    9627            4 :             Bytes::from_static(b"value 9@0x10"),
    9628            4 :         ];
    9629            4 : 
    9630            4 :         let expected_result_at_lsn_20 = [
    9631            4 :             Bytes::from_static(b"value 0@0x10"),
    9632            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9633            4 :             Bytes::from_static(b"value 2@0x10"),
    9634            4 :             Bytes::from_static(b"value 3@0x10"),
    9635            4 :             Bytes::from_static(b"value 4@0x10"),
    9636            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9637            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9638            4 :             Bytes::from_static(b"value 7@0x10"),
    9639            4 :             Bytes::from_static(b"value 8@0x10"),
    9640            4 :             Bytes::from_static(b"value 9@0x10"),
    9641            4 :         ];
    9642            4 : 
    9643            4 :         let expected_result_at_lsn_10 = [
    9644            4 :             Bytes::from_static(b"value 0@0x10"),
    9645            4 :             Bytes::from_static(b"value 1@0x10"),
    9646            4 :             Bytes::from_static(b"value 2@0x10"),
    9647            4 :             Bytes::from_static(b"value 3@0x10"),
    9648            4 :             Bytes::from_static(b"value 4@0x10"),
    9649            4 :             Bytes::from_static(b"value 5@0x10"),
    9650            4 :             Bytes::from_static(b"value 6@0x10"),
    9651            4 :             Bytes::from_static(b"value 7@0x10"),
    9652            4 :             Bytes::from_static(b"value 8@0x10"),
    9653            4 :             Bytes::from_static(b"value 9@0x10"),
    9654            4 :         ];
    9655            4 : 
    9656           24 :         let verify_result = || async {
    9657           24 :             let gc_horizon = {
    9658           24 :                 let gc_info = tline.gc_info.read().unwrap();
    9659           24 :                 gc_info.cutoffs.time
    9660            4 :             };
    9661          264 :             for idx in 0..10 {
    9662          240 :                 assert_eq!(
    9663          240 :                     tline
    9664          240 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9665          240 :                         .await
    9666          240 :                         .unwrap(),
    9667          240 :                     &expected_result[idx]
    9668            4 :                 );
    9669          240 :                 assert_eq!(
    9670          240 :                     tline
    9671          240 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9672          240 :                         .await
    9673          240 :                         .unwrap(),
    9674          240 :                     &expected_result_at_gc_horizon[idx]
    9675            4 :                 );
    9676          240 :                 assert_eq!(
    9677          240 :                     tline
    9678          240 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9679          240 :                         .await
    9680          240 :                         .unwrap(),
    9681          240 :                     &expected_result_at_lsn_20[idx]
    9682            4 :                 );
    9683          240 :                 assert_eq!(
    9684          240 :                     tline
    9685          240 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9686          240 :                         .await
    9687          240 :                         .unwrap(),
    9688          240 :                     &expected_result_at_lsn_10[idx]
    9689            4 :                 );
    9690            4 :             }
    9691           48 :         };
    9692            4 : 
    9693            4 :         verify_result().await;
    9694            4 : 
    9695            4 :         let cancel = CancellationToken::new();
    9696            4 :         let mut dryrun_flags = EnumSet::new();
    9697            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9698            4 : 
    9699            4 :         tline
    9700            4 :             .compact_with_gc(
    9701            4 :                 &cancel,
    9702            4 :                 CompactOptions {
    9703            4 :                     flags: dryrun_flags,
    9704            4 :                     ..Default::default()
    9705            4 :                 },
    9706            4 :                 &ctx,
    9707            4 :             )
    9708            4 :             .await
    9709            4 :             .unwrap();
    9710            4 :         // 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
    9711            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9712            4 :         verify_result().await;
    9713            4 : 
    9714            4 :         tline
    9715            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9716            4 :             .await
    9717            4 :             .unwrap();
    9718            4 :         verify_result().await;
    9719            4 : 
    9720            4 :         // compact again
    9721            4 :         tline
    9722            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9723            4 :             .await
    9724            4 :             .unwrap();
    9725            4 :         verify_result().await;
    9726            4 : 
    9727            4 :         // increase GC horizon and compact again
    9728            4 :         {
    9729            4 :             tline
    9730            4 :                 .applied_gc_cutoff_lsn
    9731            4 :                 .lock_for_write()
    9732            4 :                 .store_and_unlock(Lsn(0x38))
    9733            4 :                 .wait()
    9734            4 :                 .await;
    9735            4 :             // Update GC info
    9736            4 :             let mut guard = tline.gc_info.write().unwrap();
    9737            4 :             guard.cutoffs.time = Lsn(0x38);
    9738            4 :             guard.cutoffs.space = Lsn(0x38);
    9739            4 :         }
    9740            4 :         tline
    9741            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9742            4 :             .await
    9743            4 :             .unwrap();
    9744            4 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9745            4 : 
    9746            4 :         // not increasing the GC horizon and compact again
    9747            4 :         tline
    9748            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9749            4 :             .await
    9750            4 :             .unwrap();
    9751            4 :         verify_result().await;
    9752            4 : 
    9753            4 :         Ok(())
    9754            4 :     }
    9755              : 
    9756              :     #[cfg(feature = "testing")]
    9757              :     #[tokio::test]
    9758            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9759            4 :     {
    9760            4 :         let harness =
    9761            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9762            4 :                 .await?;
    9763            4 :         let (tenant, ctx) = harness.load().await;
    9764            4 : 
    9765          704 :         fn get_key(id: u32) -> Key {
    9766          704 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9767          704 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9768          704 :             key.field6 = id;
    9769          704 :             key
    9770          704 :         }
    9771            4 : 
    9772            4 :         let img_layer = (0..10)
    9773           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9774            4 :             .collect_vec();
    9775            4 : 
    9776            4 :         let delta1 = vec![
    9777            4 :             (
    9778            4 :                 get_key(1),
    9779            4 :                 Lsn(0x20),
    9780            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9781            4 :             ),
    9782            4 :             (
    9783            4 :                 get_key(1),
    9784            4 :                 Lsn(0x28),
    9785            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9786            4 :             ),
    9787            4 :         ];
    9788            4 :         let delta2 = vec![
    9789            4 :             (
    9790            4 :                 get_key(1),
    9791            4 :                 Lsn(0x30),
    9792            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9793            4 :             ),
    9794            4 :             (
    9795            4 :                 get_key(1),
    9796            4 :                 Lsn(0x38),
    9797            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9798            4 :             ),
    9799            4 :         ];
    9800            4 :         let delta3 = vec![
    9801            4 :             (
    9802            4 :                 get_key(8),
    9803            4 :                 Lsn(0x48),
    9804            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9805            4 :             ),
    9806            4 :             (
    9807            4 :                 get_key(9),
    9808            4 :                 Lsn(0x48),
    9809            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9810            4 :             ),
    9811            4 :         ];
    9812            4 : 
    9813            4 :         let tline = tenant
    9814            4 :             .create_test_timeline_with_layers(
    9815            4 :                 TIMELINE_ID,
    9816            4 :                 Lsn(0x10),
    9817            4 :                 DEFAULT_PG_VERSION,
    9818            4 :                 &ctx,
    9819            4 :                 Vec::new(), // in-memory layers
    9820            4 :                 vec![
    9821            4 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9822            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9823            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9824            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9825            4 :                 ], // delta layers
    9826            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9827            4 :                 Lsn(0x50),
    9828            4 :             )
    9829            4 :             .await?;
    9830            4 :         {
    9831            4 :             tline
    9832            4 :                 .applied_gc_cutoff_lsn
    9833            4 :                 .lock_for_write()
    9834            4 :                 .store_and_unlock(Lsn(0x30))
    9835            4 :                 .wait()
    9836            4 :                 .await;
    9837            4 :             // Update GC info
    9838            4 :             let mut guard = tline.gc_info.write().unwrap();
    9839            4 :             *guard = GcInfo {
    9840            4 :                 retain_lsns: vec![
    9841            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9842            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9843            4 :                 ],
    9844            4 :                 cutoffs: GcCutoffs {
    9845            4 :                     time: Lsn(0x30),
    9846            4 :                     space: Lsn(0x30),
    9847            4 :                 },
    9848            4 :                 leases: Default::default(),
    9849            4 :                 within_ancestor_pitr: false,
    9850            4 :             };
    9851            4 :         }
    9852            4 : 
    9853            4 :         let expected_result = [
    9854            4 :             Bytes::from_static(b"value 0@0x10"),
    9855            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9856            4 :             Bytes::from_static(b"value 2@0x10"),
    9857            4 :             Bytes::from_static(b"value 3@0x10"),
    9858            4 :             Bytes::from_static(b"value 4@0x10"),
    9859            4 :             Bytes::from_static(b"value 5@0x10"),
    9860            4 :             Bytes::from_static(b"value 6@0x10"),
    9861            4 :             Bytes::from_static(b"value 7@0x10"),
    9862            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9863            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9864            4 :         ];
    9865            4 : 
    9866            4 :         let expected_result_at_gc_horizon = [
    9867            4 :             Bytes::from_static(b"value 0@0x10"),
    9868            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9869            4 :             Bytes::from_static(b"value 2@0x10"),
    9870            4 :             Bytes::from_static(b"value 3@0x10"),
    9871            4 :             Bytes::from_static(b"value 4@0x10"),
    9872            4 :             Bytes::from_static(b"value 5@0x10"),
    9873            4 :             Bytes::from_static(b"value 6@0x10"),
    9874            4 :             Bytes::from_static(b"value 7@0x10"),
    9875            4 :             Bytes::from_static(b"value 8@0x10"),
    9876            4 :             Bytes::from_static(b"value 9@0x10"),
    9877            4 :         ];
    9878            4 : 
    9879            4 :         let expected_result_at_lsn_20 = [
    9880            4 :             Bytes::from_static(b"value 0@0x10"),
    9881            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9882            4 :             Bytes::from_static(b"value 2@0x10"),
    9883            4 :             Bytes::from_static(b"value 3@0x10"),
    9884            4 :             Bytes::from_static(b"value 4@0x10"),
    9885            4 :             Bytes::from_static(b"value 5@0x10"),
    9886            4 :             Bytes::from_static(b"value 6@0x10"),
    9887            4 :             Bytes::from_static(b"value 7@0x10"),
    9888            4 :             Bytes::from_static(b"value 8@0x10"),
    9889            4 :             Bytes::from_static(b"value 9@0x10"),
    9890            4 :         ];
    9891            4 : 
    9892            4 :         let expected_result_at_lsn_10 = [
    9893            4 :             Bytes::from_static(b"value 0@0x10"),
    9894            4 :             Bytes::from_static(b"value 1@0x10"),
    9895            4 :             Bytes::from_static(b"value 2@0x10"),
    9896            4 :             Bytes::from_static(b"value 3@0x10"),
    9897            4 :             Bytes::from_static(b"value 4@0x10"),
    9898            4 :             Bytes::from_static(b"value 5@0x10"),
    9899            4 :             Bytes::from_static(b"value 6@0x10"),
    9900            4 :             Bytes::from_static(b"value 7@0x10"),
    9901            4 :             Bytes::from_static(b"value 8@0x10"),
    9902            4 :             Bytes::from_static(b"value 9@0x10"),
    9903            4 :         ];
    9904            4 : 
    9905           16 :         let verify_result = || async {
    9906           16 :             let gc_horizon = {
    9907           16 :                 let gc_info = tline.gc_info.read().unwrap();
    9908           16 :                 gc_info.cutoffs.time
    9909            4 :             };
    9910          176 :             for idx in 0..10 {
    9911          160 :                 assert_eq!(
    9912          160 :                     tline
    9913          160 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9914          160 :                         .await
    9915          160 :                         .unwrap(),
    9916          160 :                     &expected_result[idx]
    9917            4 :                 );
    9918          160 :                 assert_eq!(
    9919          160 :                     tline
    9920          160 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9921          160 :                         .await
    9922          160 :                         .unwrap(),
    9923          160 :                     &expected_result_at_gc_horizon[idx]
    9924            4 :                 );
    9925          160 :                 assert_eq!(
    9926          160 :                     tline
    9927          160 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9928          160 :                         .await
    9929          160 :                         .unwrap(),
    9930          160 :                     &expected_result_at_lsn_20[idx]
    9931            4 :                 );
    9932          160 :                 assert_eq!(
    9933          160 :                     tline
    9934          160 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9935          160 :                         .await
    9936          160 :                         .unwrap(),
    9937          160 :                     &expected_result_at_lsn_10[idx]
    9938            4 :                 );
    9939            4 :             }
    9940           32 :         };
    9941            4 : 
    9942            4 :         verify_result().await;
    9943            4 : 
    9944            4 :         let cancel = CancellationToken::new();
    9945            4 :         let mut dryrun_flags = EnumSet::new();
    9946            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9947            4 : 
    9948            4 :         tline
    9949            4 :             .compact_with_gc(
    9950            4 :                 &cancel,
    9951            4 :                 CompactOptions {
    9952            4 :                     flags: dryrun_flags,
    9953            4 :                     ..Default::default()
    9954            4 :                 },
    9955            4 :                 &ctx,
    9956            4 :             )
    9957            4 :             .await
    9958            4 :             .unwrap();
    9959            4 :         // 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
    9960            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9961            4 :         verify_result().await;
    9962            4 : 
    9963            4 :         tline
    9964            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9965            4 :             .await
    9966            4 :             .unwrap();
    9967            4 :         verify_result().await;
    9968            4 : 
    9969            4 :         // compact again
    9970            4 :         tline
    9971            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9972            4 :             .await
    9973            4 :             .unwrap();
    9974            4 :         verify_result().await;
    9975            4 : 
    9976            4 :         Ok(())
    9977            4 :     }
    9978              : 
    9979              :     #[cfg(feature = "testing")]
    9980              :     #[tokio::test]
    9981            4 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9982            4 :         use models::CompactLsnRange;
    9983            4 : 
    9984            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9985            4 :         let (tenant, ctx) = harness.load().await;
    9986            4 : 
    9987          332 :         fn get_key(id: u32) -> Key {
    9988          332 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9989          332 :             key.field6 = id;
    9990          332 :             key
    9991          332 :         }
    9992            4 : 
    9993            4 :         let img_layer = (0..10)
    9994           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9995            4 :             .collect_vec();
    9996            4 : 
    9997            4 :         let delta1 = vec![
    9998            4 :             (
    9999            4 :                 get_key(1),
   10000            4 :                 Lsn(0x20),
   10001            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10002            4 :             ),
   10003            4 :             (
   10004            4 :                 get_key(2),
   10005            4 :                 Lsn(0x30),
   10006            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10007            4 :             ),
   10008            4 :             (
   10009            4 :                 get_key(3),
   10010            4 :                 Lsn(0x28),
   10011            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10012            4 :             ),
   10013            4 :             (
   10014            4 :                 get_key(3),
   10015            4 :                 Lsn(0x30),
   10016            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10017            4 :             ),
   10018            4 :             (
   10019            4 :                 get_key(3),
   10020            4 :                 Lsn(0x40),
   10021            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10022            4 :             ),
   10023            4 :         ];
   10024            4 :         let delta2 = vec![
   10025            4 :             (
   10026            4 :                 get_key(5),
   10027            4 :                 Lsn(0x20),
   10028            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10029            4 :             ),
   10030            4 :             (
   10031            4 :                 get_key(6),
   10032            4 :                 Lsn(0x20),
   10033            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10034            4 :             ),
   10035            4 :         ];
   10036            4 :         let delta3 = vec![
   10037            4 :             (
   10038            4 :                 get_key(8),
   10039            4 :                 Lsn(0x48),
   10040            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10041            4 :             ),
   10042            4 :             (
   10043            4 :                 get_key(9),
   10044            4 :                 Lsn(0x48),
   10045            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10046            4 :             ),
   10047            4 :         ];
   10048            4 : 
   10049            4 :         let parent_tline = tenant
   10050            4 :             .create_test_timeline_with_layers(
   10051            4 :                 TIMELINE_ID,
   10052            4 :                 Lsn(0x10),
   10053            4 :                 DEFAULT_PG_VERSION,
   10054            4 :                 &ctx,
   10055            4 :                 vec![],                       // in-memory layers
   10056            4 :                 vec![],                       // delta layers
   10057            4 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10058            4 :                 Lsn(0x18),
   10059            4 :             )
   10060            4 :             .await?;
   10061            4 : 
   10062            4 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10063            4 : 
   10064            4 :         let branch_tline = tenant
   10065            4 :             .branch_timeline_test_with_layers(
   10066            4 :                 &parent_tline,
   10067            4 :                 NEW_TIMELINE_ID,
   10068            4 :                 Some(Lsn(0x18)),
   10069            4 :                 &ctx,
   10070            4 :                 vec![
   10071            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10072            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10073            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10074            4 :                 ], // delta layers
   10075            4 :                 vec![], // image layers
   10076            4 :                 Lsn(0x50),
   10077            4 :             )
   10078            4 :             .await?;
   10079            4 : 
   10080            4 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10081            4 : 
   10082            4 :         {
   10083            4 :             parent_tline
   10084            4 :                 .applied_gc_cutoff_lsn
   10085            4 :                 .lock_for_write()
   10086            4 :                 .store_and_unlock(Lsn(0x10))
   10087            4 :                 .wait()
   10088            4 :                 .await;
   10089            4 :             // Update GC info
   10090            4 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10091            4 :             *guard = GcInfo {
   10092            4 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10093            4 :                 cutoffs: GcCutoffs {
   10094            4 :                     time: Lsn(0x10),
   10095            4 :                     space: Lsn(0x10),
   10096            4 :                 },
   10097            4 :                 leases: Default::default(),
   10098            4 :                 within_ancestor_pitr: false,
   10099            4 :             };
   10100            4 :         }
   10101            4 : 
   10102            4 :         {
   10103            4 :             branch_tline
   10104            4 :                 .applied_gc_cutoff_lsn
   10105            4 :                 .lock_for_write()
   10106            4 :                 .store_and_unlock(Lsn(0x50))
   10107            4 :                 .wait()
   10108            4 :                 .await;
   10109            4 :             // Update GC info
   10110            4 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10111            4 :             *guard = GcInfo {
   10112            4 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10113            4 :                 cutoffs: GcCutoffs {
   10114            4 :                     time: Lsn(0x50),
   10115            4 :                     space: Lsn(0x50),
   10116            4 :                 },
   10117            4 :                 leases: Default::default(),
   10118            4 :                 within_ancestor_pitr: false,
   10119            4 :             };
   10120            4 :         }
   10121            4 : 
   10122            4 :         let expected_result_at_gc_horizon = [
   10123            4 :             Bytes::from_static(b"value 0@0x10"),
   10124            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10125            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10126            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10127            4 :             Bytes::from_static(b"value 4@0x10"),
   10128            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10129            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10130            4 :             Bytes::from_static(b"value 7@0x10"),
   10131            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10132            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10133            4 :         ];
   10134            4 : 
   10135            4 :         let expected_result_at_lsn_40 = [
   10136            4 :             Bytes::from_static(b"value 0@0x10"),
   10137            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10138            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10139            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10140            4 :             Bytes::from_static(b"value 4@0x10"),
   10141            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10142            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10143            4 :             Bytes::from_static(b"value 7@0x10"),
   10144            4 :             Bytes::from_static(b"value 8@0x10"),
   10145            4 :             Bytes::from_static(b"value 9@0x10"),
   10146            4 :         ];
   10147            4 : 
   10148           12 :         let verify_result = || async {
   10149          132 :             for idx in 0..10 {
   10150          120 :                 assert_eq!(
   10151          120 :                     branch_tline
   10152          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10153          120 :                         .await
   10154          120 :                         .unwrap(),
   10155          120 :                     &expected_result_at_gc_horizon[idx]
   10156            4 :                 );
   10157          120 :                 assert_eq!(
   10158          120 :                     branch_tline
   10159          120 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10160          120 :                         .await
   10161          120 :                         .unwrap(),
   10162          120 :                     &expected_result_at_lsn_40[idx]
   10163            4 :                 );
   10164            4 :             }
   10165           24 :         };
   10166            4 : 
   10167            4 :         verify_result().await;
   10168            4 : 
   10169            4 :         let cancel = CancellationToken::new();
   10170            4 :         branch_tline
   10171            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10172            4 :             .await
   10173            4 :             .unwrap();
   10174            4 : 
   10175            4 :         verify_result().await;
   10176            4 : 
   10177            4 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10178            4 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10179            4 :         branch_tline
   10180            4 :             .compact_with_gc(
   10181            4 :                 &cancel,
   10182            4 :                 CompactOptions {
   10183            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10184            4 :                     ..Default::default()
   10185            4 :                 },
   10186            4 :                 &ctx,
   10187            4 :             )
   10188            4 :             .await
   10189            4 :             .unwrap();
   10190            4 : 
   10191            4 :         verify_result().await;
   10192            4 : 
   10193            4 :         Ok(())
   10194            4 :     }
   10195              : 
   10196              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10197              :     // Create an image arrangement where we have to read at different LSN ranges
   10198              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10199              :     // a delta layer. Like so:
   10200              :     //
   10201              :     //     A      B
   10202              :     // +----------------+ -> delta_layer
   10203              :     // |                |                           ^ lsn
   10204              :     // |       =========|-> nested_image_layer      |
   10205              :     // |       C        |                           |
   10206              :     // +----------------+                           |
   10207              :     // ======== -> baseline_image_layer             +-------> key
   10208              :     //
   10209              :     //
   10210              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10211              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10212              :     #[cfg(feature = "testing")]
   10213              :     #[tokio::test]
   10214            4 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10215            4 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10216            4 :         let (tenant, ctx) = harness.load().await;
   10217            4 : 
   10218            4 :         let will_init_keys = [2, 6];
   10219           88 :         fn get_key(id: u32) -> Key {
   10220           88 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10221           88 :             key.field6 = id;
   10222           88 :             key
   10223           88 :         }
   10224            4 : 
   10225            4 :         let mut expected_key_values = HashMap::new();
   10226            4 : 
   10227            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10228            4 :         let mut baseline_img_layer = Vec::new();
   10229           24 :         for i in 0..5 {
   10230           20 :             let key = get_key(i);
   10231           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10232           20 : 
   10233           20 :             let removed = expected_key_values.insert(key, value.clone());
   10234           20 :             assert!(removed.is_none());
   10235            4 : 
   10236           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10237            4 :         }
   10238            4 : 
   10239            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10240            4 :         let mut nested_img_layer = Vec::new();
   10241           24 :         for i in 5..10 {
   10242           20 :             let key = get_key(i);
   10243           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10244           20 : 
   10245           20 :             let removed = expected_key_values.insert(key, value.clone());
   10246           20 :             assert!(removed.is_none());
   10247            4 : 
   10248           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10249            4 :         }
   10250            4 : 
   10251            4 :         let mut delta_layer_spec = Vec::default();
   10252            4 :         let delta_layer_start_lsn = Lsn(0x20);
   10253            4 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10254            4 : 
   10255           44 :         for i in 0..10 {
   10256           40 :             let key = get_key(i);
   10257           40 :             let key_in_nested = nested_img_layer
   10258           40 :                 .iter()
   10259          160 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10260           40 :             let lsn = {
   10261           40 :                 if key_in_nested {
   10262           20 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10263            4 :                 } else {
   10264           20 :                     delta_layer_start_lsn
   10265            4 :                 }
   10266            4 :             };
   10267            4 : 
   10268           40 :             let will_init = will_init_keys.contains(&i);
   10269           40 :             if will_init {
   10270            8 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10271            8 : 
   10272            8 :                 expected_key_values.insert(key, "".to_string());
   10273           32 :             } else {
   10274           32 :                 let delta = format!("@{lsn}");
   10275           32 :                 delta_layer_spec.push((
   10276           32 :                     key,
   10277           32 :                     lsn,
   10278           32 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10279           32 :                 ));
   10280           32 : 
   10281           32 :                 expected_key_values
   10282           32 :                     .get_mut(&key)
   10283           32 :                     .expect("An image exists for each key")
   10284           32 :                     .push_str(delta.as_str());
   10285           32 :             }
   10286           40 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10287            4 :         }
   10288            4 : 
   10289            4 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10290            4 : 
   10291            4 :         assert!(
   10292            4 :             nested_image_layer_lsn > delta_layer_start_lsn
   10293            4 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10294            4 :         );
   10295            4 : 
   10296            4 :         let tline = tenant
   10297            4 :             .create_test_timeline_with_layers(
   10298            4 :                 TIMELINE_ID,
   10299            4 :                 baseline_image_layer_lsn,
   10300            4 :                 DEFAULT_PG_VERSION,
   10301            4 :                 &ctx,
   10302            4 :                 vec![], // in-memory layers
   10303            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10304            4 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10305            4 :                     delta_layer_spec,
   10306            4 :                 )], // delta layers
   10307            4 :                 vec![
   10308            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10309            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10310            4 :                 ], // image layers
   10311            4 :                 delta_layer_end_lsn,
   10312            4 :             )
   10313            4 :             .await?;
   10314            4 : 
   10315            4 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10316            4 :         let results = tline
   10317            4 :             .get_vectored(
   10318            4 :                 keyspace,
   10319            4 :                 delta_layer_end_lsn,
   10320            4 :                 IoConcurrency::sequential(),
   10321            4 :                 &ctx,
   10322            4 :             )
   10323            4 :             .await
   10324            4 :             .expect("No vectored errors");
   10325           44 :         for (key, res) in results {
   10326           40 :             let value = res.expect("No key errors");
   10327           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10328           40 :             assert_eq!(value, Bytes::from(expected_value));
   10329            4 :         }
   10330            4 : 
   10331            4 :         Ok(())
   10332            4 :     }
   10333              : 
   10334              :     #[cfg(feature = "testing")]
   10335              :     #[tokio::test]
   10336            4 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   10337            4 :         let harness =
   10338            4 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   10339            4 :         let (tenant, ctx) = harness.load().await;
   10340            4 : 
   10341            4 :         let will_init_keys = [2, 6];
   10342          128 :         fn get_key(id: u32) -> Key {
   10343          128 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10344          128 :             key.field6 = id;
   10345          128 :             key
   10346          128 :         }
   10347            4 : 
   10348            4 :         let mut expected_key_values = HashMap::new();
   10349            4 : 
   10350            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10351            4 :         let mut baseline_img_layer = Vec::new();
   10352           24 :         for i in 0..5 {
   10353           20 :             let key = get_key(i);
   10354           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10355           20 : 
   10356           20 :             let removed = expected_key_values.insert(key, value.clone());
   10357           20 :             assert!(removed.is_none());
   10358            4 : 
   10359           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10360            4 :         }
   10361            4 : 
   10362            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10363            4 :         let mut nested_img_layer = Vec::new();
   10364           24 :         for i in 5..10 {
   10365           20 :             let key = get_key(i);
   10366           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10367           20 : 
   10368           20 :             let removed = expected_key_values.insert(key, value.clone());
   10369           20 :             assert!(removed.is_none());
   10370            4 : 
   10371           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10372            4 :         }
   10373            4 : 
   10374            4 :         let frozen_layer = {
   10375            4 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   10376            4 :             let mut data = Vec::new();
   10377           44 :             for i in 0..10 {
   10378           40 :                 let key = get_key(i);
   10379           40 :                 let key_in_nested = nested_img_layer
   10380           40 :                     .iter()
   10381          160 :                     .any(|(key_with_img, _)| *key_with_img == key);
   10382           40 :                 let lsn = {
   10383           40 :                     if key_in_nested {
   10384           20 :                         Lsn(nested_image_layer_lsn.0 + 5)
   10385            4 :                     } else {
   10386           20 :                         lsn_range.start
   10387            4 :                     }
   10388            4 :                 };
   10389            4 : 
   10390           40 :                 let will_init = will_init_keys.contains(&i);
   10391           40 :                 if will_init {
   10392            8 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10393            8 : 
   10394            8 :                     expected_key_values.insert(key, "".to_string());
   10395           32 :                 } else {
   10396           32 :                     let delta = format!("@{lsn}");
   10397           32 :                     data.push((
   10398           32 :                         key,
   10399           32 :                         lsn,
   10400           32 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10401           32 :                     ));
   10402           32 : 
   10403           32 :                     expected_key_values
   10404           32 :                         .get_mut(&key)
   10405           32 :                         .expect("An image exists for each key")
   10406           32 :                         .push_str(delta.as_str());
   10407           32 :                 }
   10408            4 :             }
   10409            4 : 
   10410            4 :             InMemoryLayerTestDesc {
   10411            4 :                 lsn_range,
   10412            4 :                 is_open: false,
   10413            4 :                 data,
   10414            4 :             }
   10415            4 :         };
   10416            4 : 
   10417            4 :         let (open_layer, last_record_lsn) = {
   10418            4 :             let start_lsn = Lsn(0x70);
   10419            4 :             let mut data = Vec::new();
   10420            4 :             let mut end_lsn = Lsn(0);
   10421           44 :             for i in 0..10 {
   10422           40 :                 let key = get_key(i);
   10423           40 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   10424           40 :                 let delta = format!("@{lsn}");
   10425           40 :                 data.push((
   10426           40 :                     key,
   10427           40 :                     lsn,
   10428           40 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10429           40 :                 ));
   10430           40 : 
   10431           40 :                 expected_key_values
   10432           40 :                     .get_mut(&key)
   10433           40 :                     .expect("An image exists for each key")
   10434           40 :                     .push_str(delta.as_str());
   10435           40 : 
   10436           40 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   10437           40 :             }
   10438            4 : 
   10439            4 :             (
   10440            4 :                 InMemoryLayerTestDesc {
   10441            4 :                     lsn_range: start_lsn..Lsn::MAX,
   10442            4 :                     is_open: true,
   10443            4 :                     data,
   10444            4 :                 },
   10445            4 :                 end_lsn,
   10446            4 :             )
   10447            4 :         };
   10448            4 : 
   10449            4 :         assert!(
   10450            4 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   10451            4 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   10452            4 :         );
   10453            4 : 
   10454            4 :         let tline = tenant
   10455            4 :             .create_test_timeline_with_layers(
   10456            4 :                 TIMELINE_ID,
   10457            4 :                 baseline_image_layer_lsn,
   10458            4 :                 DEFAULT_PG_VERSION,
   10459            4 :                 &ctx,
   10460            4 :                 vec![open_layer, frozen_layer], // in-memory layers
   10461            4 :                 Vec::new(),                     // delta layers
   10462            4 :                 vec![
   10463            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10464            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10465            4 :                 ], // image layers
   10466            4 :                 last_record_lsn,
   10467            4 :             )
   10468            4 :             .await?;
   10469            4 : 
   10470            4 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10471            4 :         let results = tline
   10472            4 :             .get_vectored(keyspace, last_record_lsn, IoConcurrency::sequential(), &ctx)
   10473            4 :             .await
   10474            4 :             .expect("No vectored errors");
   10475           44 :         for (key, res) in results {
   10476           40 :             let value = res.expect("No key errors");
   10477           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10478           40 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   10479            4 : 
   10480           40 :             tracing::info!("key={key} value={expected_value}");
   10481            4 :         }
   10482            4 : 
   10483            4 :         Ok(())
   10484            4 :     }
   10485              : 
   10486          428 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   10487          428 :         (
   10488          428 :             k1.is_delta,
   10489          428 :             k1.key_range.start,
   10490          428 :             k1.key_range.end,
   10491          428 :             k1.lsn_range.start,
   10492          428 :             k1.lsn_range.end,
   10493          428 :         )
   10494          428 :             .cmp(&(
   10495          428 :                 k2.is_delta,
   10496          428 :                 k2.key_range.start,
   10497          428 :                 k2.key_range.end,
   10498          428 :                 k2.lsn_range.start,
   10499          428 :                 k2.lsn_range.end,
   10500          428 :             ))
   10501          428 :     }
   10502              : 
   10503           48 :     async fn inspect_and_sort(
   10504           48 :         tline: &Arc<Timeline>,
   10505           48 :         filter: Option<std::ops::Range<Key>>,
   10506           48 :     ) -> Vec<PersistentLayerKey> {
   10507           48 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   10508           48 :         if let Some(filter) = filter {
   10509          216 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   10510           44 :         }
   10511           48 :         all_layers.sort_by(sort_layer_key);
   10512           48 :         all_layers
   10513           48 :     }
   10514              : 
   10515              :     #[cfg(feature = "testing")]
   10516           44 :     fn check_layer_map_key_eq(
   10517           44 :         mut left: Vec<PersistentLayerKey>,
   10518           44 :         mut right: Vec<PersistentLayerKey>,
   10519           44 :     ) {
   10520           44 :         left.sort_by(sort_layer_key);
   10521           44 :         right.sort_by(sort_layer_key);
   10522           44 :         if left != right {
   10523            0 :             eprintln!("---LEFT---");
   10524            0 :             for left in left.iter() {
   10525            0 :                 eprintln!("{}", left);
   10526            0 :             }
   10527            0 :             eprintln!("---RIGHT---");
   10528            0 :             for right in right.iter() {
   10529            0 :                 eprintln!("{}", right);
   10530            0 :             }
   10531            0 :             assert_eq!(left, right);
   10532           44 :         }
   10533           44 :     }
   10534              : 
   10535              :     #[cfg(feature = "testing")]
   10536              :     #[tokio::test]
   10537            4 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   10538            4 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   10539            4 :         let (tenant, ctx) = harness.load().await;
   10540            4 : 
   10541          364 :         fn get_key(id: u32) -> Key {
   10542          364 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10543          364 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10544          364 :             key.field6 = id;
   10545          364 :             key
   10546          364 :         }
   10547            4 : 
   10548            4 :         // img layer at 0x10
   10549            4 :         let img_layer = (0..10)
   10550           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10551            4 :             .collect_vec();
   10552            4 : 
   10553            4 :         let delta1 = vec![
   10554            4 :             (
   10555            4 :                 get_key(1),
   10556            4 :                 Lsn(0x20),
   10557            4 :                 Value::Image(Bytes::from("value 1@0x20")),
   10558            4 :             ),
   10559            4 :             (
   10560            4 :                 get_key(2),
   10561            4 :                 Lsn(0x30),
   10562            4 :                 Value::Image(Bytes::from("value 2@0x30")),
   10563            4 :             ),
   10564            4 :             (
   10565            4 :                 get_key(3),
   10566            4 :                 Lsn(0x40),
   10567            4 :                 Value::Image(Bytes::from("value 3@0x40")),
   10568            4 :             ),
   10569            4 :         ];
   10570            4 :         let delta2 = vec![
   10571            4 :             (
   10572            4 :                 get_key(5),
   10573            4 :                 Lsn(0x20),
   10574            4 :                 Value::Image(Bytes::from("value 5@0x20")),
   10575            4 :             ),
   10576            4 :             (
   10577            4 :                 get_key(6),
   10578            4 :                 Lsn(0x20),
   10579            4 :                 Value::Image(Bytes::from("value 6@0x20")),
   10580            4 :             ),
   10581            4 :         ];
   10582            4 :         let delta3 = vec![
   10583            4 :             (
   10584            4 :                 get_key(8),
   10585            4 :                 Lsn(0x48),
   10586            4 :                 Value::Image(Bytes::from("value 8@0x48")),
   10587            4 :             ),
   10588            4 :             (
   10589            4 :                 get_key(9),
   10590            4 :                 Lsn(0x48),
   10591            4 :                 Value::Image(Bytes::from("value 9@0x48")),
   10592            4 :             ),
   10593            4 :         ];
   10594            4 : 
   10595            4 :         let tline = tenant
   10596            4 :             .create_test_timeline_with_layers(
   10597            4 :                 TIMELINE_ID,
   10598            4 :                 Lsn(0x10),
   10599            4 :                 DEFAULT_PG_VERSION,
   10600            4 :                 &ctx,
   10601            4 :                 vec![], // in-memory layers
   10602            4 :                 vec![
   10603            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10604            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10605            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10606            4 :                 ], // delta layers
   10607            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10608            4 :                 Lsn(0x50),
   10609            4 :             )
   10610            4 :             .await?;
   10611            4 : 
   10612            4 :         {
   10613            4 :             tline
   10614            4 :                 .applied_gc_cutoff_lsn
   10615            4 :                 .lock_for_write()
   10616            4 :                 .store_and_unlock(Lsn(0x30))
   10617            4 :                 .wait()
   10618            4 :                 .await;
   10619            4 :             // Update GC info
   10620            4 :             let mut guard = tline.gc_info.write().unwrap();
   10621            4 :             *guard = GcInfo {
   10622            4 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10623            4 :                 cutoffs: GcCutoffs {
   10624            4 :                     time: Lsn(0x30),
   10625            4 :                     space: Lsn(0x30),
   10626            4 :                 },
   10627            4 :                 leases: Default::default(),
   10628            4 :                 within_ancestor_pitr: false,
   10629            4 :             };
   10630            4 :         }
   10631            4 : 
   10632            4 :         let cancel = CancellationToken::new();
   10633            4 : 
   10634            4 :         // Do a partial compaction on key range 0..2
   10635            4 :         tline
   10636            4 :             .compact_with_gc(
   10637            4 :                 &cancel,
   10638            4 :                 CompactOptions {
   10639            4 :                     flags: EnumSet::new(),
   10640            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10641            4 :                     ..Default::default()
   10642            4 :                 },
   10643            4 :                 &ctx,
   10644            4 :             )
   10645            4 :             .await
   10646            4 :             .unwrap();
   10647            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10648            4 :         check_layer_map_key_eq(
   10649            4 :             all_layers,
   10650            4 :             vec![
   10651            4 :                 // newly-generated image layer for the partial compaction range 0-2
   10652            4 :                 PersistentLayerKey {
   10653            4 :                     key_range: get_key(0)..get_key(2),
   10654            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10655            4 :                     is_delta: false,
   10656            4 :                 },
   10657            4 :                 PersistentLayerKey {
   10658            4 :                     key_range: get_key(0)..get_key(10),
   10659            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10660            4 :                     is_delta: false,
   10661            4 :                 },
   10662            4 :                 // delta1 is split and the second part is rewritten
   10663            4 :                 PersistentLayerKey {
   10664            4 :                     key_range: get_key(2)..get_key(4),
   10665            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10666            4 :                     is_delta: true,
   10667            4 :                 },
   10668            4 :                 PersistentLayerKey {
   10669            4 :                     key_range: get_key(5)..get_key(7),
   10670            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10671            4 :                     is_delta: true,
   10672            4 :                 },
   10673            4 :                 PersistentLayerKey {
   10674            4 :                     key_range: get_key(8)..get_key(10),
   10675            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10676            4 :                     is_delta: true,
   10677            4 :                 },
   10678            4 :             ],
   10679            4 :         );
   10680            4 : 
   10681            4 :         // Do a partial compaction on key range 2..4
   10682            4 :         tline
   10683            4 :             .compact_with_gc(
   10684            4 :                 &cancel,
   10685            4 :                 CompactOptions {
   10686            4 :                     flags: EnumSet::new(),
   10687            4 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   10688            4 :                     ..Default::default()
   10689            4 :                 },
   10690            4 :                 &ctx,
   10691            4 :             )
   10692            4 :             .await
   10693            4 :             .unwrap();
   10694            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10695            4 :         check_layer_map_key_eq(
   10696            4 :             all_layers,
   10697            4 :             vec![
   10698            4 :                 PersistentLayerKey {
   10699            4 :                     key_range: get_key(0)..get_key(2),
   10700            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10701            4 :                     is_delta: false,
   10702            4 :                 },
   10703            4 :                 PersistentLayerKey {
   10704            4 :                     key_range: get_key(0)..get_key(10),
   10705            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10706            4 :                     is_delta: false,
   10707            4 :                 },
   10708            4 :                 // image layer generated for the compaction range 2-4
   10709            4 :                 PersistentLayerKey {
   10710            4 :                     key_range: get_key(2)..get_key(4),
   10711            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10712            4 :                     is_delta: false,
   10713            4 :                 },
   10714            4 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10715            4 :                 PersistentLayerKey {
   10716            4 :                     key_range: get_key(2)..get_key(4),
   10717            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10718            4 :                     is_delta: true,
   10719            4 :                 },
   10720            4 :                 PersistentLayerKey {
   10721            4 :                     key_range: get_key(5)..get_key(7),
   10722            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10723            4 :                     is_delta: true,
   10724            4 :                 },
   10725            4 :                 PersistentLayerKey {
   10726            4 :                     key_range: get_key(8)..get_key(10),
   10727            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10728            4 :                     is_delta: true,
   10729            4 :                 },
   10730            4 :             ],
   10731            4 :         );
   10732            4 : 
   10733            4 :         // Do a partial compaction on key range 4..9
   10734            4 :         tline
   10735            4 :             .compact_with_gc(
   10736            4 :                 &cancel,
   10737            4 :                 CompactOptions {
   10738            4 :                     flags: EnumSet::new(),
   10739            4 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   10740            4 :                     ..Default::default()
   10741            4 :                 },
   10742            4 :                 &ctx,
   10743            4 :             )
   10744            4 :             .await
   10745            4 :             .unwrap();
   10746            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10747            4 :         check_layer_map_key_eq(
   10748            4 :             all_layers,
   10749            4 :             vec![
   10750            4 :                 PersistentLayerKey {
   10751            4 :                     key_range: get_key(0)..get_key(2),
   10752            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10753            4 :                     is_delta: false,
   10754            4 :                 },
   10755            4 :                 PersistentLayerKey {
   10756            4 :                     key_range: get_key(0)..get_key(10),
   10757            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10758            4 :                     is_delta: false,
   10759            4 :                 },
   10760            4 :                 PersistentLayerKey {
   10761            4 :                     key_range: get_key(2)..get_key(4),
   10762            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10763            4 :                     is_delta: false,
   10764            4 :                 },
   10765            4 :                 PersistentLayerKey {
   10766            4 :                     key_range: get_key(2)..get_key(4),
   10767            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10768            4 :                     is_delta: true,
   10769            4 :                 },
   10770            4 :                 // image layer generated for this compaction range
   10771            4 :                 PersistentLayerKey {
   10772            4 :                     key_range: get_key(4)..get_key(9),
   10773            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10774            4 :                     is_delta: false,
   10775            4 :                 },
   10776            4 :                 PersistentLayerKey {
   10777            4 :                     key_range: get_key(8)..get_key(10),
   10778            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10779            4 :                     is_delta: true,
   10780            4 :                 },
   10781            4 :             ],
   10782            4 :         );
   10783            4 : 
   10784            4 :         // Do a partial compaction on key range 9..10
   10785            4 :         tline
   10786            4 :             .compact_with_gc(
   10787            4 :                 &cancel,
   10788            4 :                 CompactOptions {
   10789            4 :                     flags: EnumSet::new(),
   10790            4 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   10791            4 :                     ..Default::default()
   10792            4 :                 },
   10793            4 :                 &ctx,
   10794            4 :             )
   10795            4 :             .await
   10796            4 :             .unwrap();
   10797            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10798            4 :         check_layer_map_key_eq(
   10799            4 :             all_layers,
   10800            4 :             vec![
   10801            4 :                 PersistentLayerKey {
   10802            4 :                     key_range: get_key(0)..get_key(2),
   10803            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10804            4 :                     is_delta: false,
   10805            4 :                 },
   10806            4 :                 PersistentLayerKey {
   10807            4 :                     key_range: get_key(0)..get_key(10),
   10808            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10809            4 :                     is_delta: false,
   10810            4 :                 },
   10811            4 :                 PersistentLayerKey {
   10812            4 :                     key_range: get_key(2)..get_key(4),
   10813            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10814            4 :                     is_delta: false,
   10815            4 :                 },
   10816            4 :                 PersistentLayerKey {
   10817            4 :                     key_range: get_key(2)..get_key(4),
   10818            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10819            4 :                     is_delta: true,
   10820            4 :                 },
   10821            4 :                 PersistentLayerKey {
   10822            4 :                     key_range: get_key(4)..get_key(9),
   10823            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10824            4 :                     is_delta: false,
   10825            4 :                 },
   10826            4 :                 // image layer generated for the compaction range
   10827            4 :                 PersistentLayerKey {
   10828            4 :                     key_range: get_key(9)..get_key(10),
   10829            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10830            4 :                     is_delta: false,
   10831            4 :                 },
   10832            4 :                 PersistentLayerKey {
   10833            4 :                     key_range: get_key(8)..get_key(10),
   10834            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10835            4 :                     is_delta: true,
   10836            4 :                 },
   10837            4 :             ],
   10838            4 :         );
   10839            4 : 
   10840            4 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10841            4 :         tline
   10842            4 :             .compact_with_gc(
   10843            4 :                 &cancel,
   10844            4 :                 CompactOptions {
   10845            4 :                     flags: EnumSet::new(),
   10846            4 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   10847            4 :                     ..Default::default()
   10848            4 :                 },
   10849            4 :                 &ctx,
   10850            4 :             )
   10851            4 :             .await
   10852            4 :             .unwrap();
   10853            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10854            4 :         check_layer_map_key_eq(
   10855            4 :             all_layers,
   10856            4 :             vec![
   10857            4 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10858            4 :                 PersistentLayerKey {
   10859            4 :                     key_range: get_key(0)..get_key(10),
   10860            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10861            4 :                     is_delta: false,
   10862            4 :                 },
   10863            4 :                 PersistentLayerKey {
   10864            4 :                     key_range: get_key(2)..get_key(4),
   10865            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10866            4 :                     is_delta: true,
   10867            4 :                 },
   10868            4 :                 PersistentLayerKey {
   10869            4 :                     key_range: get_key(8)..get_key(10),
   10870            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10871            4 :                     is_delta: true,
   10872            4 :                 },
   10873            4 :             ],
   10874            4 :         );
   10875            4 :         Ok(())
   10876            4 :     }
   10877              : 
   10878              :     #[cfg(feature = "testing")]
   10879              :     #[tokio::test]
   10880            4 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10881            4 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10882            4 :             .await
   10883            4 :             .unwrap();
   10884            4 :         let (tenant, ctx) = harness.load().await;
   10885            4 :         let tline_parent = tenant
   10886            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10887            4 :             .await
   10888            4 :             .unwrap();
   10889            4 :         let tline_child = tenant
   10890            4 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10891            4 :             .await
   10892            4 :             .unwrap();
   10893            4 :         {
   10894            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10895            4 :             assert_eq!(
   10896            4 :                 gc_info_parent.retain_lsns,
   10897            4 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10898            4 :             );
   10899            4 :         }
   10900            4 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10901            4 :         tline_child
   10902            4 :             .remote_client
   10903            4 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10904            4 :             .unwrap();
   10905            4 :         tline_child.remote_client.wait_completion().await.unwrap();
   10906            4 :         offload_timeline(&tenant, &tline_child)
   10907            4 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10908            4 :             .await.unwrap();
   10909            4 :         let child_timeline_id = tline_child.timeline_id;
   10910            4 :         Arc::try_unwrap(tline_child).unwrap();
   10911            4 : 
   10912            4 :         {
   10913            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10914            4 :             assert_eq!(
   10915            4 :                 gc_info_parent.retain_lsns,
   10916            4 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10917            4 :             );
   10918            4 :         }
   10919            4 : 
   10920            4 :         tenant
   10921            4 :             .get_offloaded_timeline(child_timeline_id)
   10922            4 :             .unwrap()
   10923            4 :             .defuse_for_tenant_drop();
   10924            4 : 
   10925            4 :         Ok(())
   10926            4 :     }
   10927              : 
   10928              :     #[cfg(feature = "testing")]
   10929              :     #[tokio::test]
   10930            4 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   10931            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   10932            4 :         let (tenant, ctx) = harness.load().await;
   10933            4 : 
   10934          592 :         fn get_key(id: u32) -> Key {
   10935          592 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10936          592 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10937          592 :             key.field6 = id;
   10938          592 :             key
   10939          592 :         }
   10940            4 : 
   10941            4 :         let img_layer = (0..10)
   10942           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10943            4 :             .collect_vec();
   10944            4 : 
   10945            4 :         let delta1 = vec![(
   10946            4 :             get_key(1),
   10947            4 :             Lsn(0x20),
   10948            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10949            4 :         )];
   10950            4 :         let delta4 = vec![(
   10951            4 :             get_key(1),
   10952            4 :             Lsn(0x28),
   10953            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10954            4 :         )];
   10955            4 :         let delta2 = vec![
   10956            4 :             (
   10957            4 :                 get_key(1),
   10958            4 :                 Lsn(0x30),
   10959            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10960            4 :             ),
   10961            4 :             (
   10962            4 :                 get_key(1),
   10963            4 :                 Lsn(0x38),
   10964            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10965            4 :             ),
   10966            4 :         ];
   10967            4 :         let delta3 = vec![
   10968            4 :             (
   10969            4 :                 get_key(8),
   10970            4 :                 Lsn(0x48),
   10971            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10972            4 :             ),
   10973            4 :             (
   10974            4 :                 get_key(9),
   10975            4 :                 Lsn(0x48),
   10976            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10977            4 :             ),
   10978            4 :         ];
   10979            4 : 
   10980            4 :         let tline = tenant
   10981            4 :             .create_test_timeline_with_layers(
   10982            4 :                 TIMELINE_ID,
   10983            4 :                 Lsn(0x10),
   10984            4 :                 DEFAULT_PG_VERSION,
   10985            4 :                 &ctx,
   10986            4 :                 vec![], // in-memory layers
   10987            4 :                 vec![
   10988            4 :                     // delta1/2/4 only contain a single key but multiple updates
   10989            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10990            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10991            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10992            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10993            4 :                 ], // delta layers
   10994            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10995            4 :                 Lsn(0x50),
   10996            4 :             )
   10997            4 :             .await?;
   10998            4 :         {
   10999            4 :             tline
   11000            4 :                 .applied_gc_cutoff_lsn
   11001            4 :                 .lock_for_write()
   11002            4 :                 .store_and_unlock(Lsn(0x30))
   11003            4 :                 .wait()
   11004            4 :                 .await;
   11005            4 :             // Update GC info
   11006            4 :             let mut guard = tline.gc_info.write().unwrap();
   11007            4 :             *guard = GcInfo {
   11008            4 :                 retain_lsns: vec![
   11009            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11010            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11011            4 :                 ],
   11012            4 :                 cutoffs: GcCutoffs {
   11013            4 :                     time: Lsn(0x30),
   11014            4 :                     space: Lsn(0x30),
   11015            4 :                 },
   11016            4 :                 leases: Default::default(),
   11017            4 :                 within_ancestor_pitr: false,
   11018            4 :             };
   11019            4 :         }
   11020            4 : 
   11021            4 :         let expected_result = [
   11022            4 :             Bytes::from_static(b"value 0@0x10"),
   11023            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11024            4 :             Bytes::from_static(b"value 2@0x10"),
   11025            4 :             Bytes::from_static(b"value 3@0x10"),
   11026            4 :             Bytes::from_static(b"value 4@0x10"),
   11027            4 :             Bytes::from_static(b"value 5@0x10"),
   11028            4 :             Bytes::from_static(b"value 6@0x10"),
   11029            4 :             Bytes::from_static(b"value 7@0x10"),
   11030            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11031            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11032            4 :         ];
   11033            4 : 
   11034            4 :         let expected_result_at_gc_horizon = [
   11035            4 :             Bytes::from_static(b"value 0@0x10"),
   11036            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11037            4 :             Bytes::from_static(b"value 2@0x10"),
   11038            4 :             Bytes::from_static(b"value 3@0x10"),
   11039            4 :             Bytes::from_static(b"value 4@0x10"),
   11040            4 :             Bytes::from_static(b"value 5@0x10"),
   11041            4 :             Bytes::from_static(b"value 6@0x10"),
   11042            4 :             Bytes::from_static(b"value 7@0x10"),
   11043            4 :             Bytes::from_static(b"value 8@0x10"),
   11044            4 :             Bytes::from_static(b"value 9@0x10"),
   11045            4 :         ];
   11046            4 : 
   11047            4 :         let expected_result_at_lsn_20 = [
   11048            4 :             Bytes::from_static(b"value 0@0x10"),
   11049            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11050            4 :             Bytes::from_static(b"value 2@0x10"),
   11051            4 :             Bytes::from_static(b"value 3@0x10"),
   11052            4 :             Bytes::from_static(b"value 4@0x10"),
   11053            4 :             Bytes::from_static(b"value 5@0x10"),
   11054            4 :             Bytes::from_static(b"value 6@0x10"),
   11055            4 :             Bytes::from_static(b"value 7@0x10"),
   11056            4 :             Bytes::from_static(b"value 8@0x10"),
   11057            4 :             Bytes::from_static(b"value 9@0x10"),
   11058            4 :         ];
   11059            4 : 
   11060            4 :         let expected_result_at_lsn_10 = [
   11061            4 :             Bytes::from_static(b"value 0@0x10"),
   11062            4 :             Bytes::from_static(b"value 1@0x10"),
   11063            4 :             Bytes::from_static(b"value 2@0x10"),
   11064            4 :             Bytes::from_static(b"value 3@0x10"),
   11065            4 :             Bytes::from_static(b"value 4@0x10"),
   11066            4 :             Bytes::from_static(b"value 5@0x10"),
   11067            4 :             Bytes::from_static(b"value 6@0x10"),
   11068            4 :             Bytes::from_static(b"value 7@0x10"),
   11069            4 :             Bytes::from_static(b"value 8@0x10"),
   11070            4 :             Bytes::from_static(b"value 9@0x10"),
   11071            4 :         ];
   11072            4 : 
   11073           12 :         let verify_result = || async {
   11074           12 :             let gc_horizon = {
   11075           12 :                 let gc_info = tline.gc_info.read().unwrap();
   11076           12 :                 gc_info.cutoffs.time
   11077            4 :             };
   11078          132 :             for idx in 0..10 {
   11079          120 :                 assert_eq!(
   11080          120 :                     tline
   11081          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11082          120 :                         .await
   11083          120 :                         .unwrap(),
   11084          120 :                     &expected_result[idx]
   11085            4 :                 );
   11086          120 :                 assert_eq!(
   11087          120 :                     tline
   11088          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11089          120 :                         .await
   11090          120 :                         .unwrap(),
   11091          120 :                     &expected_result_at_gc_horizon[idx]
   11092            4 :                 );
   11093          120 :                 assert_eq!(
   11094          120 :                     tline
   11095          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11096          120 :                         .await
   11097          120 :                         .unwrap(),
   11098          120 :                     &expected_result_at_lsn_20[idx]
   11099            4 :                 );
   11100          120 :                 assert_eq!(
   11101          120 :                     tline
   11102          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11103          120 :                         .await
   11104          120 :                         .unwrap(),
   11105          120 :                     &expected_result_at_lsn_10[idx]
   11106            4 :                 );
   11107            4 :             }
   11108           24 :         };
   11109            4 : 
   11110            4 :         verify_result().await;
   11111            4 : 
   11112            4 :         let cancel = CancellationToken::new();
   11113            4 :         tline
   11114            4 :             .compact_with_gc(
   11115            4 :                 &cancel,
   11116            4 :                 CompactOptions {
   11117            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   11118            4 :                     ..Default::default()
   11119            4 :                 },
   11120            4 :                 &ctx,
   11121            4 :             )
   11122            4 :             .await
   11123            4 :             .unwrap();
   11124            4 :         verify_result().await;
   11125            4 : 
   11126            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11127            4 :         check_layer_map_key_eq(
   11128            4 :             all_layers,
   11129            4 :             vec![
   11130            4 :                 // The original image layer, not compacted
   11131            4 :                 PersistentLayerKey {
   11132            4 :                     key_range: get_key(0)..get_key(10),
   11133            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11134            4 :                     is_delta: false,
   11135            4 :                 },
   11136            4 :                 // Delta layer below the specified above_lsn not compacted
   11137            4 :                 PersistentLayerKey {
   11138            4 :                     key_range: get_key(1)..get_key(2),
   11139            4 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   11140            4 :                     is_delta: true,
   11141            4 :                 },
   11142            4 :                 // Delta layer compacted above the LSN
   11143            4 :                 PersistentLayerKey {
   11144            4 :                     key_range: get_key(1)..get_key(10),
   11145            4 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   11146            4 :                     is_delta: true,
   11147            4 :                 },
   11148            4 :             ],
   11149            4 :         );
   11150            4 : 
   11151            4 :         // compact again
   11152            4 :         tline
   11153            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11154            4 :             .await
   11155            4 :             .unwrap();
   11156            4 :         verify_result().await;
   11157            4 : 
   11158            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11159            4 :         check_layer_map_key_eq(
   11160            4 :             all_layers,
   11161            4 :             vec![
   11162            4 :                 // The compacted image layer (full key range)
   11163            4 :                 PersistentLayerKey {
   11164            4 :                     key_range: Key::MIN..Key::MAX,
   11165            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11166            4 :                     is_delta: false,
   11167            4 :                 },
   11168            4 :                 // All other data in the delta layer
   11169            4 :                 PersistentLayerKey {
   11170            4 :                     key_range: get_key(1)..get_key(10),
   11171            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11172            4 :                     is_delta: true,
   11173            4 :                 },
   11174            4 :             ],
   11175            4 :         );
   11176            4 : 
   11177            4 :         Ok(())
   11178            4 :     }
   11179              : 
   11180              :     #[cfg(feature = "testing")]
   11181              :     #[tokio::test]
   11182            4 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   11183            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   11184            4 :         let (tenant, ctx) = harness.load().await;
   11185            4 : 
   11186         1016 :         fn get_key(id: u32) -> Key {
   11187         1016 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11188         1016 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11189         1016 :             key.field6 = id;
   11190         1016 :             key
   11191         1016 :         }
   11192            4 : 
   11193            4 :         let img_layer = (0..10)
   11194           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11195            4 :             .collect_vec();
   11196            4 : 
   11197            4 :         let delta1 = vec![(
   11198            4 :             get_key(1),
   11199            4 :             Lsn(0x20),
   11200            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11201            4 :         )];
   11202            4 :         let delta4 = vec![(
   11203            4 :             get_key(1),
   11204            4 :             Lsn(0x28),
   11205            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11206            4 :         )];
   11207            4 :         let delta2 = vec![
   11208            4 :             (
   11209            4 :                 get_key(1),
   11210            4 :                 Lsn(0x30),
   11211            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11212            4 :             ),
   11213            4 :             (
   11214            4 :                 get_key(1),
   11215            4 :                 Lsn(0x38),
   11216            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11217            4 :             ),
   11218            4 :         ];
   11219            4 :         let delta3 = vec![
   11220            4 :             (
   11221            4 :                 get_key(8),
   11222            4 :                 Lsn(0x48),
   11223            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11224            4 :             ),
   11225            4 :             (
   11226            4 :                 get_key(9),
   11227            4 :                 Lsn(0x48),
   11228            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11229            4 :             ),
   11230            4 :         ];
   11231            4 : 
   11232            4 :         let tline = tenant
   11233            4 :             .create_test_timeline_with_layers(
   11234            4 :                 TIMELINE_ID,
   11235            4 :                 Lsn(0x10),
   11236            4 :                 DEFAULT_PG_VERSION,
   11237            4 :                 &ctx,
   11238            4 :                 vec![], // in-memory layers
   11239            4 :                 vec![
   11240            4 :                     // delta1/2/4 only contain a single key but multiple updates
   11241            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11242            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11243            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11244            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11245            4 :                 ], // delta layers
   11246            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11247            4 :                 Lsn(0x50),
   11248            4 :             )
   11249            4 :             .await?;
   11250            4 :         {
   11251            4 :             tline
   11252            4 :                 .applied_gc_cutoff_lsn
   11253            4 :                 .lock_for_write()
   11254            4 :                 .store_and_unlock(Lsn(0x30))
   11255            4 :                 .wait()
   11256            4 :                 .await;
   11257            4 :             // Update GC info
   11258            4 :             let mut guard = tline.gc_info.write().unwrap();
   11259            4 :             *guard = GcInfo {
   11260            4 :                 retain_lsns: vec![
   11261            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11262            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11263            4 :                 ],
   11264            4 :                 cutoffs: GcCutoffs {
   11265            4 :                     time: Lsn(0x30),
   11266            4 :                     space: Lsn(0x30),
   11267            4 :                 },
   11268            4 :                 leases: Default::default(),
   11269            4 :                 within_ancestor_pitr: false,
   11270            4 :             };
   11271            4 :         }
   11272            4 : 
   11273            4 :         let expected_result = [
   11274            4 :             Bytes::from_static(b"value 0@0x10"),
   11275            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11276            4 :             Bytes::from_static(b"value 2@0x10"),
   11277            4 :             Bytes::from_static(b"value 3@0x10"),
   11278            4 :             Bytes::from_static(b"value 4@0x10"),
   11279            4 :             Bytes::from_static(b"value 5@0x10"),
   11280            4 :             Bytes::from_static(b"value 6@0x10"),
   11281            4 :             Bytes::from_static(b"value 7@0x10"),
   11282            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11283            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11284            4 :         ];
   11285            4 : 
   11286            4 :         let expected_result_at_gc_horizon = [
   11287            4 :             Bytes::from_static(b"value 0@0x10"),
   11288            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11289            4 :             Bytes::from_static(b"value 2@0x10"),
   11290            4 :             Bytes::from_static(b"value 3@0x10"),
   11291            4 :             Bytes::from_static(b"value 4@0x10"),
   11292            4 :             Bytes::from_static(b"value 5@0x10"),
   11293            4 :             Bytes::from_static(b"value 6@0x10"),
   11294            4 :             Bytes::from_static(b"value 7@0x10"),
   11295            4 :             Bytes::from_static(b"value 8@0x10"),
   11296            4 :             Bytes::from_static(b"value 9@0x10"),
   11297            4 :         ];
   11298            4 : 
   11299            4 :         let expected_result_at_lsn_20 = [
   11300            4 :             Bytes::from_static(b"value 0@0x10"),
   11301            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11302            4 :             Bytes::from_static(b"value 2@0x10"),
   11303            4 :             Bytes::from_static(b"value 3@0x10"),
   11304            4 :             Bytes::from_static(b"value 4@0x10"),
   11305            4 :             Bytes::from_static(b"value 5@0x10"),
   11306            4 :             Bytes::from_static(b"value 6@0x10"),
   11307            4 :             Bytes::from_static(b"value 7@0x10"),
   11308            4 :             Bytes::from_static(b"value 8@0x10"),
   11309            4 :             Bytes::from_static(b"value 9@0x10"),
   11310            4 :         ];
   11311            4 : 
   11312            4 :         let expected_result_at_lsn_10 = [
   11313            4 :             Bytes::from_static(b"value 0@0x10"),
   11314            4 :             Bytes::from_static(b"value 1@0x10"),
   11315            4 :             Bytes::from_static(b"value 2@0x10"),
   11316            4 :             Bytes::from_static(b"value 3@0x10"),
   11317            4 :             Bytes::from_static(b"value 4@0x10"),
   11318            4 :             Bytes::from_static(b"value 5@0x10"),
   11319            4 :             Bytes::from_static(b"value 6@0x10"),
   11320            4 :             Bytes::from_static(b"value 7@0x10"),
   11321            4 :             Bytes::from_static(b"value 8@0x10"),
   11322            4 :             Bytes::from_static(b"value 9@0x10"),
   11323            4 :         ];
   11324            4 : 
   11325           20 :         let verify_result = || async {
   11326           20 :             let gc_horizon = {
   11327           20 :                 let gc_info = tline.gc_info.read().unwrap();
   11328           20 :                 gc_info.cutoffs.time
   11329            4 :             };
   11330          220 :             for idx in 0..10 {
   11331          200 :                 assert_eq!(
   11332          200 :                     tline
   11333          200 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11334          200 :                         .await
   11335          200 :                         .unwrap(),
   11336          200 :                     &expected_result[idx]
   11337            4 :                 );
   11338          200 :                 assert_eq!(
   11339          200 :                     tline
   11340          200 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11341          200 :                         .await
   11342          200 :                         .unwrap(),
   11343          200 :                     &expected_result_at_gc_horizon[idx]
   11344            4 :                 );
   11345          200 :                 assert_eq!(
   11346          200 :                     tline
   11347          200 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11348          200 :                         .await
   11349          200 :                         .unwrap(),
   11350          200 :                     &expected_result_at_lsn_20[idx]
   11351            4 :                 );
   11352          200 :                 assert_eq!(
   11353          200 :                     tline
   11354          200 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11355          200 :                         .await
   11356          200 :                         .unwrap(),
   11357          200 :                     &expected_result_at_lsn_10[idx]
   11358            4 :                 );
   11359            4 :             }
   11360           40 :         };
   11361            4 : 
   11362            4 :         verify_result().await;
   11363            4 : 
   11364            4 :         let cancel = CancellationToken::new();
   11365            4 : 
   11366            4 :         tline
   11367            4 :             .compact_with_gc(
   11368            4 :                 &cancel,
   11369            4 :                 CompactOptions {
   11370            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11371            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   11372            4 :                     ..Default::default()
   11373            4 :                 },
   11374            4 :                 &ctx,
   11375            4 :             )
   11376            4 :             .await
   11377            4 :             .unwrap();
   11378            4 :         verify_result().await;
   11379            4 : 
   11380            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11381            4 :         check_layer_map_key_eq(
   11382            4 :             all_layers,
   11383            4 :             vec![
   11384            4 :                 // The original image layer, not compacted
   11385            4 :                 PersistentLayerKey {
   11386            4 :                     key_range: get_key(0)..get_key(10),
   11387            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11388            4 :                     is_delta: false,
   11389            4 :                 },
   11390            4 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   11391            4 :                 // the layer 0x28-0x30 into one.
   11392            4 :                 PersistentLayerKey {
   11393            4 :                     key_range: get_key(1)..get_key(2),
   11394            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11395            4 :                     is_delta: true,
   11396            4 :                 },
   11397            4 :                 // Above the upper bound and untouched
   11398            4 :                 PersistentLayerKey {
   11399            4 :                     key_range: get_key(1)..get_key(2),
   11400            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11401            4 :                     is_delta: true,
   11402            4 :                 },
   11403            4 :                 // This layer is untouched
   11404            4 :                 PersistentLayerKey {
   11405            4 :                     key_range: get_key(8)..get_key(10),
   11406            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11407            4 :                     is_delta: true,
   11408            4 :                 },
   11409            4 :             ],
   11410            4 :         );
   11411            4 : 
   11412            4 :         tline
   11413            4 :             .compact_with_gc(
   11414            4 :                 &cancel,
   11415            4 :                 CompactOptions {
   11416            4 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   11417            4 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   11418            4 :                     ..Default::default()
   11419            4 :                 },
   11420            4 :                 &ctx,
   11421            4 :             )
   11422            4 :             .await
   11423            4 :             .unwrap();
   11424            4 :         verify_result().await;
   11425            4 : 
   11426            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11427            4 :         check_layer_map_key_eq(
   11428            4 :             all_layers,
   11429            4 :             vec![
   11430            4 :                 // The original image layer, not compacted
   11431            4 :                 PersistentLayerKey {
   11432            4 :                     key_range: get_key(0)..get_key(10),
   11433            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11434            4 :                     is_delta: false,
   11435            4 :                 },
   11436            4 :                 // Not in the compaction key range, uncompacted
   11437            4 :                 PersistentLayerKey {
   11438            4 :                     key_range: get_key(1)..get_key(2),
   11439            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11440            4 :                     is_delta: true,
   11441            4 :                 },
   11442            4 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   11443            4 :                 PersistentLayerKey {
   11444            4 :                     key_range: get_key(1)..get_key(2),
   11445            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11446            4 :                     is_delta: true,
   11447            4 :                 },
   11448            4 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   11449            4 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   11450            4 :                 // becomes 0x50.
   11451            4 :                 PersistentLayerKey {
   11452            4 :                     key_range: get_key(8)..get_key(10),
   11453            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11454            4 :                     is_delta: true,
   11455            4 :                 },
   11456            4 :             ],
   11457            4 :         );
   11458            4 : 
   11459            4 :         // compact again
   11460            4 :         tline
   11461            4 :             .compact_with_gc(
   11462            4 :                 &cancel,
   11463            4 :                 CompactOptions {
   11464            4 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   11465            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   11466            4 :                     ..Default::default()
   11467            4 :                 },
   11468            4 :                 &ctx,
   11469            4 :             )
   11470            4 :             .await
   11471            4 :             .unwrap();
   11472            4 :         verify_result().await;
   11473            4 : 
   11474            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11475            4 :         check_layer_map_key_eq(
   11476            4 :             all_layers,
   11477            4 :             vec![
   11478            4 :                 // The original image layer, not compacted
   11479            4 :                 PersistentLayerKey {
   11480            4 :                     key_range: get_key(0)..get_key(10),
   11481            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11482            4 :                     is_delta: false,
   11483            4 :                 },
   11484            4 :                 // The range gets compacted
   11485            4 :                 PersistentLayerKey {
   11486            4 :                     key_range: get_key(1)..get_key(2),
   11487            4 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   11488            4 :                     is_delta: true,
   11489            4 :                 },
   11490            4 :                 // Not touched during this iteration of compaction
   11491            4 :                 PersistentLayerKey {
   11492            4 :                     key_range: get_key(8)..get_key(10),
   11493            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11494            4 :                     is_delta: true,
   11495            4 :                 },
   11496            4 :             ],
   11497            4 :         );
   11498            4 : 
   11499            4 :         // final full compaction
   11500            4 :         tline
   11501            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11502            4 :             .await
   11503            4 :             .unwrap();
   11504            4 :         verify_result().await;
   11505            4 : 
   11506            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11507            4 :         check_layer_map_key_eq(
   11508            4 :             all_layers,
   11509            4 :             vec![
   11510            4 :                 // The compacted image layer (full key range)
   11511            4 :                 PersistentLayerKey {
   11512            4 :                     key_range: Key::MIN..Key::MAX,
   11513            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11514            4 :                     is_delta: false,
   11515            4 :                 },
   11516            4 :                 // All other data in the delta layer
   11517            4 :                 PersistentLayerKey {
   11518            4 :                     key_range: get_key(1)..get_key(10),
   11519            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11520            4 :                     is_delta: true,
   11521            4 :                 },
   11522            4 :             ],
   11523            4 :         );
   11524            4 : 
   11525            4 :         Ok(())
   11526            4 :     }
   11527              : }
        

Generated by: LCOV version 2.1-beta