LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 6c6fe25ecc82be7eef3e957667d85acf2b969737.info Lines: 78.4 % 9556 7496
Test Date: 2025-04-16 17:36:39 Functions: 62.2 % 468 291

            Line data    Source code
       1              : //! Timeline repository implementation that keeps old data in layer files, and
       2              : //! the recent changes in ephemeral files.
       3              : //!
       4              : //! See tenant/*_layer.rs files. The functions here are responsible for locating
       5              : //! the correct layer for the get/put call, walking back the timeline branching
       6              : //! history as needed.
       7              : //!
       8              : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
       9              : //! directory. See docs/pageserver-storage.md for how the files are managed.
      10              : //! In addition to the layer files, there is a metadata file in the same
      11              : //! directory that contains information about the timeline, in particular its
      12              : //! parent timeline, and the last LSN that has been written to disk.
      13              : //!
      14              : 
      15              : use std::collections::hash_map::Entry;
      16              : use std::collections::{BTreeMap, HashMap, HashSet};
      17              : use std::fmt::{Debug, Display};
      18              : use std::fs::File;
      19              : use std::future::Future;
      20              : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
      21              : use std::sync::{Arc, Mutex, Weak};
      22              : use std::time::{Duration, Instant, SystemTime};
      23              : use std::{fmt, fs};
      24              : 
      25              : use anyhow::{Context, bail};
      26              : use arc_swap::ArcSwap;
      27              : use camino::{Utf8Path, Utf8PathBuf};
      28              : use chrono::NaiveDateTime;
      29              : use enumset::EnumSet;
      30              : use futures::StreamExt;
      31              : use futures::stream::FuturesUnordered;
      32              : use itertools::Itertools as _;
      33              : use once_cell::sync::Lazy;
      34              : pub use pageserver_api::models::TenantState;
      35              : use pageserver_api::models::{self, RelSizeMigration};
      36              : use pageserver_api::models::{
      37              :     CompactInfoResponse, LsnLease, TimelineArchivalState, TimelineState, TopTenantShardItem,
      38              :     WalRedoManagerStatus,
      39              : };
      40              : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
      41              : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
      42              : use remote_timeline_client::index::GcCompactionState;
      43              : use remote_timeline_client::manifest::{
      44              :     LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
      45              : };
      46              : use remote_timeline_client::{
      47              :     FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
      48              :     download_tenant_manifest,
      49              : };
      50              : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
      51              : use storage_broker::BrokerClientChannel;
      52              : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
      53              : use timeline::offload::{OffloadError, offload_timeline};
      54              : use timeline::{
      55              :     CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
      56              : };
      57              : use tokio::io::BufReader;
      58              : use tokio::sync::{Notify, Semaphore, watch};
      59              : use tokio::task::JoinSet;
      60              : use tokio_util::sync::CancellationToken;
      61              : use tracing::*;
      62              : use upload_queue::NotInitialized;
      63              : use utils::circuit_breaker::CircuitBreaker;
      64              : use utils::crashsafe::path_with_suffix_extension;
      65              : use utils::sync::gate::{Gate, GateGuard};
      66              : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
      67              : use utils::try_rcu::ArcSwapExt;
      68              : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
      69              : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
      70              : 
      71              : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf};
      72              : use self::metadata::TimelineMetadata;
      73              : use self::mgr::{GetActiveTenantError, GetTenantError};
      74              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      75              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      76              : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
      77              : use self::timeline::{
      78              :     EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
      79              : };
      80              : use crate::config::PageServerConf;
      81              : use crate::context;
      82              : use crate::context::RequestContextBuilder;
      83              : use crate::context::{DownloadBehavior, RequestContext};
      84              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
      85              : use crate::l0_flush::L0FlushGlobalState;
      86              : use crate::metrics::{
      87              :     BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
      88              :     INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_STATE_METRIC,
      89              :     TENANT_SYNTHETIC_SIZE_METRIC, remove_tenant_metrics,
      90              : };
      91              : use crate::task_mgr::TaskKind;
      92              : use crate::tenant::config::LocationMode;
      93              : use crate::tenant::gc_result::GcResult;
      94              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
      95              : use crate::tenant::remote_timeline_client::{
      96              :     INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
      97              : };
      98              : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
      99              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     100              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     101              : use crate::virtual_file::VirtualFile;
     102              : use crate::walingest::WalLagCooldown;
     103              : use crate::walredo::{PostgresRedoManager, RedoAttemptType};
     104              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
     105              : 
     106            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     107              : use utils::crashsafe;
     108              : use utils::generation::Generation;
     109              : use utils::id::TimelineId;
     110              : use utils::lsn::{Lsn, RecordLsn};
     111              : 
     112              : pub mod blob_io;
     113              : pub mod block_io;
     114              : pub mod vectored_blob_io;
     115              : 
     116              : pub mod disk_btree;
     117              : pub(crate) mod ephemeral_file;
     118              : pub mod layer_map;
     119              : 
     120              : pub mod metadata;
     121              : pub mod remote_timeline_client;
     122              : pub mod storage_layer;
     123              : 
     124              : pub mod checks;
     125              : pub mod config;
     126              : pub mod mgr;
     127              : pub mod secondary;
     128              : pub mod tasks;
     129              : pub mod upload_queue;
     130              : 
     131              : pub(crate) mod timeline;
     132              : 
     133              : pub mod size;
     134              : 
     135              : mod gc_block;
     136              : mod gc_result;
     137              : pub(crate) mod throttle;
     138              : 
     139              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     140              : 
     141              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     142              : // re-export for use in walreceiver
     143              : pub use crate::tenant::timeline::WalReceiverInfo;
     144              : 
     145              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     146              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     147              : 
     148              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     149              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     150              : 
     151              : /// References to shared objects that are passed into each tenant, such
     152              : /// as the shared remote storage client and process initialization state.
     153              : #[derive(Clone)]
     154              : pub struct TenantSharedResources {
     155              :     pub broker_client: storage_broker::BrokerClientChannel,
     156              :     pub remote_storage: GenericRemoteStorage,
     157              :     pub deletion_queue_client: DeletionQueueClient,
     158              :     pub l0_flush_global_state: L0FlushGlobalState,
     159              : }
     160              : 
     161              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     162              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     163              : /// in this struct.
     164              : #[derive(Clone)]
     165              : pub(super) struct AttachedTenantConf {
     166              :     tenant_conf: pageserver_api::models::TenantConfig,
     167              :     location: AttachedLocationConfig,
     168              :     /// The deadline before which we are blocked from GC so that
     169              :     /// leases have a chance to be renewed.
     170              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     171              : }
     172              : 
     173              : impl AttachedTenantConf {
     174          464 :     fn new(
     175          464 :         tenant_conf: pageserver_api::models::TenantConfig,
     176          464 :         location: AttachedLocationConfig,
     177          464 :     ) -> Self {
     178              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     179              :         //
     180              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     181              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     182              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     183          464 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     184          464 :             Some(
     185          464 :                 tokio::time::Instant::now()
     186          464 :                     + tenant_conf
     187          464 :                         .lsn_lease_length
     188          464 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     189          464 :             )
     190              :         } else {
     191              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     192              :             // because we don't do GC in these modes.
     193            0 :             None
     194              :         };
     195              : 
     196          464 :         Self {
     197          464 :             tenant_conf,
     198          464 :             location,
     199          464 :             lsn_lease_deadline,
     200          464 :         }
     201          464 :     }
     202              : 
     203          464 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     204          464 :         match &location_conf.mode {
     205          464 :             LocationMode::Attached(attach_conf) => {
     206          464 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     207              :             }
     208              :             LocationMode::Secondary(_) => {
     209            0 :                 anyhow::bail!(
     210            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     211            0 :                 )
     212              :             }
     213              :         }
     214          464 :     }
     215              : 
     216         1524 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     217         1524 :         self.lsn_lease_deadline
     218         1524 :             .map(|d| tokio::time::Instant::now() < d)
     219         1524 :             .unwrap_or(false)
     220         1524 :     }
     221              : }
     222              : struct TimelinePreload {
     223              :     timeline_id: TimelineId,
     224              :     client: RemoteTimelineClient,
     225              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     226              :     previous_heatmap: Option<PreviousHeatmap>,
     227              : }
     228              : 
     229              : pub(crate) struct TenantPreload {
     230              :     /// The tenant manifest from remote storage, or None if no manifest was found.
     231              :     tenant_manifest: Option<TenantManifest>,
     232              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     233              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     234              : }
     235              : 
     236              : /// When we spawn a tenant, there is a special mode for tenant creation that
     237              : /// avoids trying to read anything from remote storage.
     238              : pub(crate) enum SpawnMode {
     239              :     /// Activate as soon as possible
     240              :     Eager,
     241              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     242              :     Lazy,
     243              : }
     244              : 
     245              : ///
     246              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     247              : ///
     248              : pub struct Tenant {
     249              :     // Global pageserver config parameters
     250              :     pub conf: &'static PageServerConf,
     251              : 
     252              :     /// The value creation timestamp, used to measure activation delay, see:
     253              :     /// <https://github.com/neondatabase/neon/issues/4025>
     254              :     constructed_at: Instant,
     255              : 
     256              :     state: watch::Sender<TenantState>,
     257              : 
     258              :     // Overridden tenant-specific config parameters.
     259              :     // We keep pageserver_api::models::TenantConfig sturct here to preserve the information
     260              :     // about parameters that are not set.
     261              :     // This is necessary to allow global config updates.
     262              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     263              : 
     264              :     tenant_shard_id: TenantShardId,
     265              : 
     266              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     267              :     shard_identity: ShardIdentity,
     268              : 
     269              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     270              :     /// Does not change over the lifetime of the [`Tenant`] object.
     271              :     ///
     272              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     273              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     274              :     generation: Generation,
     275              : 
     276              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     277              : 
     278              :     /// During timeline creation, we first insert the TimelineId to the
     279              :     /// creating map, then `timelines`, then remove it from the creating map.
     280              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     281              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     282              : 
     283              :     /// Possibly offloaded and archived timelines
     284              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     285              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     286              : 
     287              :     /// The last tenant manifest known to be in remote storage. None if the manifest has not yet
     288              :     /// been either downloaded or uploaded. Always Some after tenant attach.
     289              :     ///
     290              :     /// Initially populated during tenant attach, updated via `maybe_upload_tenant_manifest`.
     291              :     ///
     292              :     /// Do not modify this directly. It is used to check whether a new manifest needs to be
     293              :     /// uploaded. The manifest is constructed in `build_tenant_manifest`, and uploaded via
     294              :     /// `maybe_upload_tenant_manifest`.
     295              :     remote_tenant_manifest: tokio::sync::Mutex<Option<TenantManifest>>,
     296              : 
     297              :     // This mutex prevents creation of new timelines during GC.
     298              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     299              :     // `timelines` mutex during all GC iteration
     300              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     301              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     302              :     // timeout...
     303              :     gc_cs: tokio::sync::Mutex<()>,
     304              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     305              : 
     306              :     // provides access to timeline data sitting in the remote storage
     307              :     pub(crate) remote_storage: GenericRemoteStorage,
     308              : 
     309              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     310              :     deletion_queue_client: DeletionQueueClient,
     311              : 
     312              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     313              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     314              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     315              : 
     316              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     317              : 
     318              :     /// Track repeated failures to compact, so that we can back off.
     319              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     320              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     321              : 
     322              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     323              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     324              : 
     325              :     /// Scheduled gc-compaction tasks.
     326              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     327              : 
     328              :     /// If the tenant is in Activating state, notify this to encourage it
     329              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     330              :     /// background warmup.
     331              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     332              : 
     333              :     /// Time it took for the tenant to activate. Zero if not active yet.
     334              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     335              : 
     336              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     337              :     // Timelines' cancellation token.
     338              :     pub(crate) cancel: CancellationToken,
     339              : 
     340              :     // Users of the Tenant such as the page service must take this Gate to avoid
     341              :     // trying to use a Tenant which is shutting down.
     342              :     pub(crate) gate: Gate,
     343              : 
     344              :     /// Throttle applied at the top of [`Timeline::get`].
     345              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     346              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     347              : 
     348              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     349              : 
     350              :     /// An ongoing timeline detach concurrency limiter.
     351              :     ///
     352              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     353              :     /// to have two running at the same time. A different one can be started if an earlier one
     354              :     /// has failed for whatever reason.
     355              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     356              : 
     357              :     /// `index_part.json` based gc blocking reason tracking.
     358              :     ///
     359              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     360              :     /// proceeding.
     361              :     pub(crate) gc_block: gc_block::GcBlock,
     362              : 
     363              :     l0_flush_global_state: L0FlushGlobalState,
     364              : }
     365              : impl std::fmt::Debug for Tenant {
     366            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     367            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     368            0 :     }
     369              : }
     370              : 
     371              : pub(crate) enum WalRedoManager {
     372              :     Prod(WalredoManagerId, PostgresRedoManager),
     373              :     #[cfg(test)]
     374              :     Test(harness::TestRedoManager),
     375              : }
     376              : 
     377              : #[derive(thiserror::Error, Debug)]
     378              : #[error("pageserver is shutting down")]
     379              : pub(crate) struct GlobalShutDown;
     380              : 
     381              : impl WalRedoManager {
     382            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     383            0 :         let id = WalredoManagerId::next();
     384            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     385            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     386            0 :         match &mut *guard {
     387            0 :             Some(map) => {
     388            0 :                 map.insert(id, Arc::downgrade(&arc));
     389            0 :                 Ok(arc)
     390              :             }
     391            0 :             None => Err(GlobalShutDown),
     392              :         }
     393            0 :     }
     394              : }
     395              : 
     396              : impl Drop for WalRedoManager {
     397           20 :     fn drop(&mut self) {
     398           20 :         match self {
     399            0 :             Self::Prod(id, _) => {
     400            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     401            0 :                 if let Some(map) = &mut *guard {
     402            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     403            0 :                 }
     404              :             }
     405              :             #[cfg(test)]
     406           20 :             Self::Test(_) => {
     407           20 :                 // Not applicable to test redo manager
     408           20 :             }
     409              :         }
     410           20 :     }
     411              : }
     412              : 
     413              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     414              : /// the walredo processes outside of the regular order.
     415              : ///
     416              : /// This is necessary to work around a systemd bug where it freezes if there are
     417              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     418              : #[allow(clippy::type_complexity)]
     419              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     420              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     421            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     422              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     423              : pub(crate) struct WalredoManagerId(u64);
     424              : impl WalredoManagerId {
     425            0 :     pub fn next() -> Self {
     426              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     427            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     428            0 :         if id == 0 {
     429            0 :             panic!(
     430            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     431            0 :             );
     432            0 :         }
     433            0 :         Self(id)
     434            0 :     }
     435              : }
     436              : 
     437              : #[cfg(test)]
     438              : impl From<harness::TestRedoManager> for WalRedoManager {
     439          464 :     fn from(mgr: harness::TestRedoManager) -> Self {
     440          464 :         Self::Test(mgr)
     441          464 :     }
     442              : }
     443              : 
     444              : impl WalRedoManager {
     445           12 :     pub(crate) async fn shutdown(&self) -> bool {
     446           12 :         match self {
     447            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     448              :             #[cfg(test)]
     449              :             Self::Test(_) => {
     450              :                 // Not applicable to test redo manager
     451           12 :                 true
     452              :             }
     453              :         }
     454           12 :     }
     455              : 
     456            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     457            0 :         match self {
     458            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     459            0 :             #[cfg(test)]
     460            0 :             Self::Test(_) => {
     461            0 :                 // Not applicable to test redo manager
     462            0 :             }
     463            0 :         }
     464            0 :     }
     465              : 
     466              :     /// # Cancel-Safety
     467              :     ///
     468              :     /// This method is cancellation-safe.
     469       107096 :     pub async fn request_redo(
     470       107096 :         &self,
     471       107096 :         key: pageserver_api::key::Key,
     472       107096 :         lsn: Lsn,
     473       107096 :         base_img: Option<(Lsn, bytes::Bytes)>,
     474       107096 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     475       107096 :         pg_version: u32,
     476       107096 :         redo_attempt_type: RedoAttemptType,
     477       107096 :     ) -> Result<bytes::Bytes, walredo::Error> {
     478       107096 :         match self {
     479            0 :             Self::Prod(_, mgr) => {
     480            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     481            0 :                     .await
     482              :             }
     483              :             #[cfg(test)]
     484       107096 :             Self::Test(mgr) => {
     485       107096 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     486       107096 :                     .await
     487              :             }
     488              :         }
     489       107096 :     }
     490              : 
     491            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     492            0 :         match self {
     493            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     494            0 :             #[cfg(test)]
     495            0 :             WalRedoManager::Test(_) => None,
     496            0 :         }
     497            0 :     }
     498              : }
     499              : 
     500              : /// A very lightweight memory representation of an offloaded timeline.
     501              : ///
     502              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     503              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     504              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     505              : /// more offloaded timelines than we can manage ones that aren't.
     506              : pub struct OffloadedTimeline {
     507              :     pub tenant_shard_id: TenantShardId,
     508              :     pub timeline_id: TimelineId,
     509              :     pub ancestor_timeline_id: Option<TimelineId>,
     510              :     /// Whether to retain the branch lsn at the ancestor or not
     511              :     pub ancestor_retain_lsn: Option<Lsn>,
     512              : 
     513              :     /// When the timeline was archived.
     514              :     ///
     515              :     /// Present for future flattening deliberations.
     516              :     pub archived_at: NaiveDateTime,
     517              : 
     518              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     519              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     520              :     pub delete_progress: TimelineDeleteProgress,
     521              : 
     522              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     523              :     pub deleted_from_ancestor: AtomicBool,
     524              : }
     525              : 
     526              : impl OffloadedTimeline {
     527              :     /// Obtains an offloaded timeline from a given timeline object.
     528              :     ///
     529              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     530              :     /// the timeline is not in a stopped state.
     531              :     /// Panics if the timeline is not archived.
     532            4 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     533            4 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     534            4 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     535            4 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     536            4 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     537            4 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     538            4 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     539            4 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     540              :             } else {
     541            0 :                 (None, None)
     542              :             };
     543            4 :         let archived_at = timeline
     544            4 :             .remote_client
     545            4 :             .archived_at_stopped_queue()?
     546            4 :             .expect("must be called on an archived timeline");
     547            4 :         Ok(Self {
     548            4 :             tenant_shard_id: timeline.tenant_shard_id,
     549            4 :             timeline_id: timeline.timeline_id,
     550            4 :             ancestor_timeline_id,
     551            4 :             ancestor_retain_lsn,
     552            4 :             archived_at,
     553            4 : 
     554            4 :             delete_progress: timeline.delete_progress.clone(),
     555            4 :             deleted_from_ancestor: AtomicBool::new(false),
     556            4 :         })
     557            4 :     }
     558            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     559            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     560            0 :         // by the `initialize_gc_info` function.
     561            0 :         let OffloadedTimelineManifest {
     562            0 :             timeline_id,
     563            0 :             ancestor_timeline_id,
     564            0 :             ancestor_retain_lsn,
     565            0 :             archived_at,
     566            0 :         } = *manifest;
     567            0 :         Self {
     568            0 :             tenant_shard_id,
     569            0 :             timeline_id,
     570            0 :             ancestor_timeline_id,
     571            0 :             ancestor_retain_lsn,
     572            0 :             archived_at,
     573            0 :             delete_progress: TimelineDeleteProgress::default(),
     574            0 :             deleted_from_ancestor: AtomicBool::new(false),
     575            0 :         }
     576            0 :     }
     577            4 :     fn manifest(&self) -> OffloadedTimelineManifest {
     578            4 :         let Self {
     579            4 :             timeline_id,
     580            4 :             ancestor_timeline_id,
     581            4 :             ancestor_retain_lsn,
     582            4 :             archived_at,
     583            4 :             ..
     584            4 :         } = self;
     585            4 :         OffloadedTimelineManifest {
     586            4 :             timeline_id: *timeline_id,
     587            4 :             ancestor_timeline_id: *ancestor_timeline_id,
     588            4 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     589            4 :             archived_at: *archived_at,
     590            4 :         }
     591            4 :     }
     592              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     593            0 :     fn delete_from_ancestor_with_timelines(
     594            0 :         &self,
     595            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     596            0 :     ) {
     597            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     598            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     599              :         {
     600            0 :             if let Some((_, ancestor_timeline)) = timelines
     601            0 :                 .iter()
     602            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     603              :             {
     604            0 :                 let removal_happened = ancestor_timeline
     605            0 :                     .gc_info
     606            0 :                     .write()
     607            0 :                     .unwrap()
     608            0 :                     .remove_child_offloaded(self.timeline_id);
     609            0 :                 if !removal_happened {
     610            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     611            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     612            0 :                 }
     613            0 :             }
     614            0 :         }
     615            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     616            0 :     }
     617              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     618              :     ///
     619              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     620            4 :     fn defuse_for_tenant_drop(&self) {
     621            4 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     622            4 :     }
     623              : }
     624              : 
     625              : impl fmt::Debug for OffloadedTimeline {
     626            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     627            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     628            0 :     }
     629              : }
     630              : 
     631              : impl Drop for OffloadedTimeline {
     632            4 :     fn drop(&mut self) {
     633            4 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     634            0 :             tracing::warn!(
     635            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     636              :                 self.timeline_id
     637              :             );
     638            4 :         }
     639            4 :     }
     640              : }
     641              : 
     642              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     643              : pub enum MaybeOffloaded {
     644              :     Yes,
     645              :     No,
     646              : }
     647              : 
     648              : #[derive(Clone, Debug)]
     649              : pub enum TimelineOrOffloaded {
     650              :     Timeline(Arc<Timeline>),
     651              :     Offloaded(Arc<OffloadedTimeline>),
     652              : }
     653              : 
     654              : impl TimelineOrOffloaded {
     655            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     656            0 :         match self {
     657            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     658            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     659              :             }
     660            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     661            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     662              :             }
     663              :         }
     664            0 :     }
     665            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     666            0 :         self.arc_ref().tenant_shard_id()
     667            0 :     }
     668            0 :     pub fn timeline_id(&self) -> TimelineId {
     669            0 :         self.arc_ref().timeline_id()
     670            0 :     }
     671            4 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     672            4 :         match self {
     673            4 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     674            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     675              :         }
     676            4 :     }
     677            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     678            0 :         match self {
     679            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     680            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     681              :         }
     682            0 :     }
     683              : }
     684              : 
     685              : pub enum TimelineOrOffloadedArcRef<'a> {
     686              :     Timeline(&'a Arc<Timeline>),
     687              :     Offloaded(&'a Arc<OffloadedTimeline>),
     688              : }
     689              : 
     690              : impl TimelineOrOffloadedArcRef<'_> {
     691            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     692            0 :         match self {
     693            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     694            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     695              :         }
     696            0 :     }
     697            0 :     pub fn timeline_id(&self) -> TimelineId {
     698            0 :         match self {
     699            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     700            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     701              :         }
     702            0 :     }
     703              : }
     704              : 
     705              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     706            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     707            0 :         Self::Timeline(timeline)
     708            0 :     }
     709              : }
     710              : 
     711              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     712            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     713            0 :         Self::Offloaded(timeline)
     714            0 :     }
     715              : }
     716              : 
     717              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     718              : pub enum GetTimelineError {
     719              :     #[error("Timeline is shutting down")]
     720              :     ShuttingDown,
     721              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     722              :     NotActive {
     723              :         tenant_id: TenantShardId,
     724              :         timeline_id: TimelineId,
     725              :         state: TimelineState,
     726              :     },
     727              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     728              :     NotFound {
     729              :         tenant_id: TenantShardId,
     730              :         timeline_id: TimelineId,
     731              :     },
     732              : }
     733              : 
     734              : #[derive(Debug, thiserror::Error)]
     735              : pub enum LoadLocalTimelineError {
     736              :     #[error("FailedToLoad")]
     737              :     Load(#[source] anyhow::Error),
     738              :     #[error("FailedToResumeDeletion")]
     739              :     ResumeDeletion(#[source] anyhow::Error),
     740              : }
     741              : 
     742              : #[derive(thiserror::Error)]
     743              : pub enum DeleteTimelineError {
     744              :     #[error("NotFound")]
     745              :     NotFound,
     746              : 
     747              :     #[error("HasChildren")]
     748              :     HasChildren(Vec<TimelineId>),
     749              : 
     750              :     #[error("Timeline deletion is already in progress")]
     751              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     752              : 
     753              :     #[error("Cancelled")]
     754              :     Cancelled,
     755              : 
     756              :     #[error(transparent)]
     757              :     Other(#[from] anyhow::Error),
     758              : }
     759              : 
     760              : impl Debug for DeleteTimelineError {
     761            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     762            0 :         match self {
     763            0 :             Self::NotFound => write!(f, "NotFound"),
     764            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     765            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     766            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     767            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     768              :         }
     769            0 :     }
     770              : }
     771              : 
     772              : #[derive(thiserror::Error)]
     773              : pub enum TimelineArchivalError {
     774              :     #[error("NotFound")]
     775              :     NotFound,
     776              : 
     777              :     #[error("Timeout")]
     778              :     Timeout,
     779              : 
     780              :     #[error("Cancelled")]
     781              :     Cancelled,
     782              : 
     783              :     #[error("ancestor is archived: {}", .0)]
     784              :     HasArchivedParent(TimelineId),
     785              : 
     786              :     #[error("HasUnarchivedChildren")]
     787              :     HasUnarchivedChildren(Vec<TimelineId>),
     788              : 
     789              :     #[error("Timeline archival is already in progress")]
     790              :     AlreadyInProgress,
     791              : 
     792              :     #[error(transparent)]
     793              :     Other(anyhow::Error),
     794              : }
     795              : 
     796              : #[derive(thiserror::Error, Debug)]
     797              : pub(crate) enum TenantManifestError {
     798              :     #[error("Remote storage error: {0}")]
     799              :     RemoteStorage(anyhow::Error),
     800              : 
     801              :     #[error("Cancelled")]
     802              :     Cancelled,
     803              : }
     804              : 
     805              : impl From<TenantManifestError> for TimelineArchivalError {
     806            0 :     fn from(e: TenantManifestError) -> Self {
     807            0 :         match e {
     808            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     809            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     810              :         }
     811            0 :     }
     812              : }
     813              : 
     814              : impl Debug for TimelineArchivalError {
     815            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     816            0 :         match self {
     817            0 :             Self::NotFound => write!(f, "NotFound"),
     818            0 :             Self::Timeout => write!(f, "Timeout"),
     819            0 :             Self::Cancelled => write!(f, "Cancelled"),
     820            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     821            0 :             Self::HasUnarchivedChildren(c) => {
     822            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     823              :             }
     824            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     825            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     826              :         }
     827            0 :     }
     828              : }
     829              : 
     830              : pub enum SetStoppingError {
     831              :     AlreadyStopping(completion::Barrier),
     832              :     Broken,
     833              : }
     834              : 
     835              : impl Debug for SetStoppingError {
     836            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     837            0 :         match self {
     838            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     839            0 :             Self::Broken => write!(f, "Broken"),
     840              :         }
     841            0 :     }
     842              : }
     843              : 
     844              : /// Arguments to [`Tenant::create_timeline`].
     845              : ///
     846              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     847              : /// is `None`, the result of the timeline create call is not deterministic.
     848              : ///
     849              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     850              : #[derive(Debug)]
     851              : pub(crate) enum CreateTimelineParams {
     852              :     Bootstrap(CreateTimelineParamsBootstrap),
     853              :     Branch(CreateTimelineParamsBranch),
     854              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     855              : }
     856              : 
     857              : #[derive(Debug)]
     858              : pub(crate) struct CreateTimelineParamsBootstrap {
     859              :     pub(crate) new_timeline_id: TimelineId,
     860              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     861              :     pub(crate) pg_version: u32,
     862              : }
     863              : 
     864              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     865              : #[derive(Debug)]
     866              : pub(crate) struct CreateTimelineParamsBranch {
     867              :     pub(crate) new_timeline_id: TimelineId,
     868              :     pub(crate) ancestor_timeline_id: TimelineId,
     869              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     870              : }
     871              : 
     872              : #[derive(Debug)]
     873              : pub(crate) struct CreateTimelineParamsImportPgdata {
     874              :     pub(crate) new_timeline_id: TimelineId,
     875              :     pub(crate) location: import_pgdata::index_part_format::Location,
     876              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     877              : }
     878              : 
     879              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     880              : ///
     881              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     882              : ///
     883              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     884              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     885              : ///
     886              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     887              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     888              : ///
     889              : /// Notes:
     890              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     891              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     892              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     893              : ///
     894              : #[derive(Debug, Clone, PartialEq, Eq)]
     895              : pub(crate) enum CreateTimelineIdempotency {
     896              :     /// NB: special treatment, see comment in [`Self`].
     897              :     FailWithConflict,
     898              :     Bootstrap {
     899              :         pg_version: u32,
     900              :     },
     901              :     /// NB: branches always have the same `pg_version` as their ancestor.
     902              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     903              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     904              :     /// determining the child branch pg_version.
     905              :     Branch {
     906              :         ancestor_timeline_id: TimelineId,
     907              :         ancestor_start_lsn: Lsn,
     908              :     },
     909              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     910              : }
     911              : 
     912              : #[derive(Debug, Clone, PartialEq, Eq)]
     913              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     914              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     915              : }
     916              : 
     917              : /// What is returned by [`Tenant::start_creating_timeline`].
     918              : #[must_use]
     919              : enum StartCreatingTimelineResult {
     920              :     CreateGuard(TimelineCreateGuard),
     921              :     Idempotent(Arc<Timeline>),
     922              : }
     923              : 
     924              : #[allow(clippy::large_enum_variant, reason = "TODO")]
     925              : enum TimelineInitAndSyncResult {
     926              :     ReadyToActivate(Arc<Timeline>),
     927              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     928              : }
     929              : 
     930              : impl TimelineInitAndSyncResult {
     931            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     932            0 :         match self {
     933            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     934            0 :             _ => None,
     935              :         }
     936            0 :     }
     937              : }
     938              : 
     939              : #[must_use]
     940              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     941              :     timeline: Arc<Timeline>,
     942              :     import_pgdata: import_pgdata::index_part_format::Root,
     943              :     guard: TimelineCreateGuard,
     944              : }
     945              : 
     946              : /// What is returned by [`Tenant::create_timeline`].
     947              : enum CreateTimelineResult {
     948              :     Created(Arc<Timeline>),
     949              :     Idempotent(Arc<Timeline>),
     950              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     951              :     /// we return this result, nor will this concrete object ever be added there.
     952              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     953              :     ImportSpawned(Arc<Timeline>),
     954              : }
     955              : 
     956              : impl CreateTimelineResult {
     957            0 :     fn discriminant(&self) -> &'static str {
     958            0 :         match self {
     959            0 :             Self::Created(_) => "Created",
     960            0 :             Self::Idempotent(_) => "Idempotent",
     961            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     962              :         }
     963            0 :     }
     964            0 :     fn timeline(&self) -> &Arc<Timeline> {
     965            0 :         match self {
     966            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     967            0 :         }
     968            0 :     }
     969              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     970              :     #[cfg(test)]
     971          472 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     972          472 :         match self {
     973          472 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     974          472 :         }
     975          472 :     }
     976              : }
     977              : 
     978              : #[derive(thiserror::Error, Debug)]
     979              : pub enum CreateTimelineError {
     980              :     #[error("creation of timeline with the given ID is in progress")]
     981              :     AlreadyCreating,
     982              :     #[error("timeline already exists with different parameters")]
     983              :     Conflict,
     984              :     #[error(transparent)]
     985              :     AncestorLsn(anyhow::Error),
     986              :     #[error("ancestor timeline is not active")]
     987              :     AncestorNotActive,
     988              :     #[error("ancestor timeline is archived")]
     989              :     AncestorArchived,
     990              :     #[error("tenant shutting down")]
     991              :     ShuttingDown,
     992              :     #[error(transparent)]
     993              :     Other(#[from] anyhow::Error),
     994              : }
     995              : 
     996              : #[derive(thiserror::Error, Debug)]
     997              : pub enum InitdbError {
     998              :     #[error("Operation was cancelled")]
     999              :     Cancelled,
    1000              :     #[error(transparent)]
    1001              :     Other(anyhow::Error),
    1002              :     #[error(transparent)]
    1003              :     Inner(postgres_initdb::Error),
    1004              : }
    1005              : 
    1006              : enum CreateTimelineCause {
    1007              :     Load,
    1008              :     Delete,
    1009              : }
    1010              : 
    1011              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1012              : enum LoadTimelineCause {
    1013              :     Attach,
    1014              :     Unoffload,
    1015              :     ImportPgdata {
    1016              :         create_guard: TimelineCreateGuard,
    1017              :         activate: ActivateTimelineArgs,
    1018              :     },
    1019              : }
    1020              : 
    1021              : #[derive(thiserror::Error, Debug)]
    1022              : pub(crate) enum GcError {
    1023              :     // The tenant is shutting down
    1024              :     #[error("tenant shutting down")]
    1025              :     TenantCancelled,
    1026              : 
    1027              :     // The tenant is shutting down
    1028              :     #[error("timeline shutting down")]
    1029              :     TimelineCancelled,
    1030              : 
    1031              :     // The tenant is in a state inelegible to run GC
    1032              :     #[error("not active")]
    1033              :     NotActive,
    1034              : 
    1035              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1036              :     #[error("not active")]
    1037              :     BadLsn { why: String },
    1038              : 
    1039              :     // A remote storage error while scheduling updates after compaction
    1040              :     #[error(transparent)]
    1041              :     Remote(anyhow::Error),
    1042              : 
    1043              :     // An error reading while calculating GC cutoffs
    1044              :     #[error(transparent)]
    1045              :     GcCutoffs(PageReconstructError),
    1046              : 
    1047              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1048              :     #[error("timeline not found")]
    1049              :     TimelineNotFound,
    1050              : }
    1051              : 
    1052              : impl From<PageReconstructError> for GcError {
    1053            0 :     fn from(value: PageReconstructError) -> Self {
    1054            0 :         match value {
    1055            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1056            0 :             other => Self::GcCutoffs(other),
    1057              :         }
    1058            0 :     }
    1059              : }
    1060              : 
    1061              : impl From<NotInitialized> for GcError {
    1062            0 :     fn from(value: NotInitialized) -> Self {
    1063            0 :         match value {
    1064            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1065            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1066              :         }
    1067            0 :     }
    1068              : }
    1069              : 
    1070              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1071            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1072            0 :         GcError::TimelineCancelled
    1073            0 :     }
    1074              : }
    1075              : 
    1076              : #[derive(thiserror::Error, Debug)]
    1077              : pub(crate) enum LoadConfigError {
    1078              :     #[error("TOML deserialization error: '{0}'")]
    1079              :     DeserializeToml(#[from] toml_edit::de::Error),
    1080              : 
    1081              :     #[error("Config not found at {0}")]
    1082              :     NotFound(Utf8PathBuf),
    1083              : }
    1084              : 
    1085              : impl Tenant {
    1086              :     /// Yet another helper for timeline initialization.
    1087              :     ///
    1088              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1089              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1090              :     /// - Downloads remote index file and adds remote files to the layer map
    1091              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1092              :     ///
    1093              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1094              :     /// it is marked as Active.
    1095              :     #[allow(clippy::too_many_arguments)]
    1096           12 :     async fn timeline_init_and_sync(
    1097           12 :         self: &Arc<Self>,
    1098           12 :         timeline_id: TimelineId,
    1099           12 :         resources: TimelineResources,
    1100           12 :         mut index_part: IndexPart,
    1101           12 :         metadata: TimelineMetadata,
    1102           12 :         previous_heatmap: Option<PreviousHeatmap>,
    1103           12 :         ancestor: Option<Arc<Timeline>>,
    1104           12 :         cause: LoadTimelineCause,
    1105           12 :         ctx: &RequestContext,
    1106           12 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1107           12 :         let tenant_id = self.tenant_shard_id;
    1108           12 : 
    1109           12 :         let import_pgdata = index_part.import_pgdata.take();
    1110           12 :         let idempotency = match &import_pgdata {
    1111            0 :             Some(import_pgdata) => {
    1112            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1113            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1114            0 :                 })
    1115              :             }
    1116              :             None => {
    1117           12 :                 if metadata.ancestor_timeline().is_none() {
    1118            8 :                     CreateTimelineIdempotency::Bootstrap {
    1119            8 :                         pg_version: metadata.pg_version(),
    1120            8 :                     }
    1121              :                 } else {
    1122            4 :                     CreateTimelineIdempotency::Branch {
    1123            4 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1124            4 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1125            4 :                     }
    1126              :                 }
    1127              :             }
    1128              :         };
    1129              : 
    1130           12 :         let (timeline, timeline_ctx) = self.create_timeline_struct(
    1131           12 :             timeline_id,
    1132           12 :             &metadata,
    1133           12 :             previous_heatmap,
    1134           12 :             ancestor.clone(),
    1135           12 :             resources,
    1136           12 :             CreateTimelineCause::Load,
    1137           12 :             idempotency.clone(),
    1138           12 :             index_part.gc_compaction.clone(),
    1139           12 :             index_part.rel_size_migration.clone(),
    1140           12 :             ctx,
    1141           12 :         )?;
    1142           12 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1143           12 :         anyhow::ensure!(
    1144           12 :             disk_consistent_lsn.is_valid(),
    1145            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1146              :         );
    1147           12 :         assert_eq!(
    1148           12 :             disk_consistent_lsn,
    1149           12 :             metadata.disk_consistent_lsn(),
    1150            0 :             "these are used interchangeably"
    1151              :         );
    1152              : 
    1153           12 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1154              : 
    1155           12 :         timeline
    1156           12 :             .load_layer_map(disk_consistent_lsn, index_part)
    1157           12 :             .await
    1158           12 :             .with_context(|| {
    1159            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1160           12 :             })?;
    1161              : 
    1162              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1163              :         // to the archival operation. To allow warming this timeline up, generate
    1164              :         // a previous heatmap which contains all visible layers in the layer map.
    1165              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1166              :         // for the timeline.
    1167           12 :         if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
    1168            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1169            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1170            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1171              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1172              :                 // If the current branch point greater than the previous one use the the heatmap
    1173              :                 // we just generated - it should include more layers.
    1174            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1175            0 :                     tline
    1176            0 :                         .previous_heatmap
    1177            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1178            0 :                 } else {
    1179            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1180              :                 }
    1181              : 
    1182            0 :                 match tline.ancestor_timeline() {
    1183            0 :                     Some(ancestor) => {
    1184            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1185              :                             // Ancestor timeline is shutting down.
    1186            0 :                             break;
    1187            0 :                         }
    1188            0 : 
    1189            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1190              :                     }
    1191            0 :                     None => {
    1192            0 :                         tline_ending_at = None;
    1193            0 :                     }
    1194              :                 }
    1195              :             }
    1196           12 :         }
    1197              : 
    1198            0 :         match import_pgdata {
    1199            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1200            0 :                 match cause {
    1201            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1202              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1203            0 :                         unreachable!(
    1204            0 :                             "ImportPgdata should not be reloading timeline import is done and persisted as such in s3"
    1205            0 :                         )
    1206              :                     }
    1207              :                 }
    1208            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1209            0 :                 if !guard.insert(timeline_id) {
    1210              :                     // We should never try and load the same timeline twice during startup
    1211            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1212            0 :                 }
    1213            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1214            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1215            0 :                     owning_tenant: self.clone(),
    1216            0 :                     timeline_id,
    1217            0 :                     idempotency,
    1218            0 :                     // The users of this specific return value don't need the timline_path in there.
    1219            0 :                     timeline_path: timeline
    1220            0 :                         .conf
    1221            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1222            0 :                 };
    1223            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1224            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1225            0 :                         timeline,
    1226            0 :                         import_pgdata,
    1227            0 :                         guard: timeline_create_guard,
    1228            0 :                     },
    1229            0 :                 ))
    1230              :             }
    1231              :             Some(_) | None => {
    1232              :                 {
    1233           12 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1234           12 :                     match timelines_accessor.entry(timeline_id) {
    1235              :                         // We should never try and load the same timeline twice during startup
    1236              :                         Entry::Occupied(_) => {
    1237            0 :                             unreachable!(
    1238            0 :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1239            0 :                             );
    1240              :                         }
    1241           12 :                         Entry::Vacant(v) => {
    1242           12 :                             v.insert(Arc::clone(&timeline));
    1243           12 :                             timeline.maybe_spawn_flush_loop();
    1244           12 :                         }
    1245              :                     }
    1246              :                 }
    1247              : 
    1248              :                 // Sanity check: a timeline should have some content.
    1249           12 :                 anyhow::ensure!(
    1250           12 :                     ancestor.is_some()
    1251            8 :                         || timeline
    1252            8 :                             .layers
    1253            8 :                             .read()
    1254            8 :                             .await
    1255            8 :                             .layer_map()
    1256            8 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1257            8 :                             .iter_historic_layers()
    1258            8 :                             .next()
    1259            8 :                             .is_some(),
    1260            0 :                     "Timeline has no ancestor and no layer files"
    1261              :                 );
    1262              : 
    1263           12 :                 match cause {
    1264           12 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1265              :                     LoadTimelineCause::ImportPgdata {
    1266            0 :                         create_guard,
    1267            0 :                         activate,
    1268            0 :                     } => {
    1269            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1270            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1271            0 :                         match activate {
    1272            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1273            0 :                                 info!("activating timeline after reload from pgdata import task");
    1274            0 :                                 timeline.activate(self.clone(), broker_client, None, &timeline_ctx);
    1275              :                             }
    1276            0 :                             ActivateTimelineArgs::No => (),
    1277              :                         }
    1278            0 :                         drop(create_guard);
    1279              :                     }
    1280              :                 }
    1281              : 
    1282           12 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1283              :             }
    1284              :         }
    1285           12 :     }
    1286              : 
    1287              :     /// Attach a tenant that's available in cloud storage.
    1288              :     ///
    1289              :     /// This returns quickly, after just creating the in-memory object
    1290              :     /// Tenant struct and launching a background task to download
    1291              :     /// the remote index files.  On return, the tenant is most likely still in
    1292              :     /// Attaching state, and it will become Active once the background task
    1293              :     /// finishes. You can use wait_until_active() to wait for the task to
    1294              :     /// complete.
    1295              :     ///
    1296              :     #[allow(clippy::too_many_arguments)]
    1297            0 :     pub(crate) fn spawn(
    1298            0 :         conf: &'static PageServerConf,
    1299            0 :         tenant_shard_id: TenantShardId,
    1300            0 :         resources: TenantSharedResources,
    1301            0 :         attached_conf: AttachedTenantConf,
    1302            0 :         shard_identity: ShardIdentity,
    1303            0 :         init_order: Option<InitializationOrder>,
    1304            0 :         mode: SpawnMode,
    1305            0 :         ctx: &RequestContext,
    1306            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1307            0 :         let wal_redo_manager =
    1308            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1309              : 
    1310              :         let TenantSharedResources {
    1311            0 :             broker_client,
    1312            0 :             remote_storage,
    1313            0 :             deletion_queue_client,
    1314            0 :             l0_flush_global_state,
    1315            0 :         } = resources;
    1316            0 : 
    1317            0 :         let attach_mode = attached_conf.location.attach_mode;
    1318            0 :         let generation = attached_conf.location.generation;
    1319            0 : 
    1320            0 :         let tenant = Arc::new(Tenant::new(
    1321            0 :             TenantState::Attaching,
    1322            0 :             conf,
    1323            0 :             attached_conf,
    1324            0 :             shard_identity,
    1325            0 :             Some(wal_redo_manager),
    1326            0 :             tenant_shard_id,
    1327            0 :             remote_storage.clone(),
    1328            0 :             deletion_queue_client,
    1329            0 :             l0_flush_global_state,
    1330            0 :         ));
    1331            0 : 
    1332            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1333            0 :         // we shut down while attaching.
    1334            0 :         let attach_gate_guard = tenant
    1335            0 :             .gate
    1336            0 :             .enter()
    1337            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1338            0 : 
    1339            0 :         // Do all the hard work in the background
    1340            0 :         let tenant_clone = Arc::clone(&tenant);
    1341            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1342            0 :         task_mgr::spawn(
    1343            0 :             &tokio::runtime::Handle::current(),
    1344            0 :             TaskKind::Attach,
    1345            0 :             tenant_shard_id,
    1346            0 :             None,
    1347            0 :             "attach tenant",
    1348            0 :             async move {
    1349            0 : 
    1350            0 :                 info!(
    1351              :                     ?attach_mode,
    1352            0 :                     "Attaching tenant"
    1353              :                 );
    1354              : 
    1355            0 :                 let _gate_guard = attach_gate_guard;
    1356            0 : 
    1357            0 :                 // Is this tenant being spawned as part of process startup?
    1358            0 :                 let starting_up = init_order.is_some();
    1359            0 :                 scopeguard::defer! {
    1360            0 :                     if starting_up {
    1361            0 :                         TENANT.startup_complete.inc();
    1362            0 :                     }
    1363            0 :                 }
    1364              : 
    1365            0 :                 fn make_broken_or_stopping(t: &Tenant, err: anyhow::Error) {
    1366            0 :                     t.state.send_modify(|state| match state {
    1367              :                         // TODO: the old code alluded to DeleteTenantFlow sometimes setting
    1368              :                         // TenantState::Stopping before we get here, but this may be outdated.
    1369              :                         // Let's find out with a testing assertion. If this doesn't fire, and the
    1370              :                         // logs don't show this happening in production, remove the Stopping cases.
    1371            0 :                         TenantState::Stopping{..} if cfg!(any(test, feature = "testing")) => {
    1372            0 :                             panic!("unexpected TenantState::Stopping during attach")
    1373              :                         }
    1374              :                         // If the tenant is cancelled, assume the error was caused by cancellation.
    1375            0 :                         TenantState::Attaching if t.cancel.is_cancelled() => {
    1376            0 :                             info!("attach cancelled, setting tenant state to Stopping: {err}");
    1377              :                             // NB: progress None tells `set_stopping` that attach has cancelled.
    1378            0 :                             *state = TenantState::Stopping { progress: None };
    1379              :                         }
    1380              :                         // According to the old code, DeleteTenantFlow may already have set this to
    1381              :                         // Stopping. Retain its progress.
    1382              :                         // TODO: there is no DeleteTenantFlow. Is this still needed? See above.
    1383            0 :                         TenantState::Stopping { progress } if t.cancel.is_cancelled() => {
    1384            0 :                             assert!(progress.is_some(), "concurrent attach cancellation");
    1385            0 :                             info!("attach cancelled, already Stopping: {err}");
    1386              :                         }
    1387              :                         // Mark the tenant as broken.
    1388              :                         TenantState::Attaching | TenantState::Stopping { .. } => {
    1389            0 :                             error!("attach failed, setting tenant state to Broken (was {state}): {err:?}");
    1390            0 :                             *state = TenantState::broken_from_reason(err.to_string())
    1391              :                         }
    1392              :                         // The attach task owns the tenant state until activated.
    1393            0 :                         state => panic!("invalid tenant state {state} during attach: {err:?}"),
    1394            0 :                     });
    1395            0 :                 }
    1396              : 
    1397              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1398            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1399            0 :                     make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1400            0 :                     return Ok(());
    1401            0 :                 }
    1402            0 : 
    1403            0 :                 let mut init_order = init_order;
    1404            0 :                 // take the completion because initial tenant loading will complete when all of
    1405            0 :                 // these tasks complete.
    1406            0 :                 let _completion = init_order
    1407            0 :                     .as_mut()
    1408            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1409            0 :                 let remote_load_completion = init_order
    1410            0 :                     .as_mut()
    1411            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1412              : 
    1413              :                 enum AttachType<'a> {
    1414              :                     /// We are attaching this tenant lazily in the background.
    1415              :                     Warmup {
    1416              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1417              :                         during_startup: bool
    1418              :                     },
    1419              :                     /// We are attaching this tenant as soon as we can, because for example an
    1420              :                     /// endpoint tried to access it.
    1421              :                     OnDemand,
    1422              :                     /// During normal operations after startup, we are attaching a tenant, and
    1423              :                     /// eager attach was requested.
    1424              :                     Normal,
    1425              :                 }
    1426              : 
    1427            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1428              :                     // Before doing any I/O, wait for at least one of:
    1429              :                     // - A client attempting to access to this tenant (on-demand loading)
    1430              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1431              : 
    1432            0 :                     tokio::select!(
    1433            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1434            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1435            0 :                             tracing::info!("Activating tenant (on-demand)");
    1436            0 :                             AttachType::OnDemand
    1437              :                         },
    1438            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1439            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1440            0 :                             tracing::info!("Activating tenant (warmup)");
    1441            0 :                             AttachType::Warmup {
    1442            0 :                                 _permit,
    1443            0 :                                 during_startup: init_order.is_some()
    1444            0 :                             }
    1445              :                         }
    1446            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1447              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1448              :                             // stayed in Activating for such a long time that shutdown found it in
    1449              :                             // that state.
    1450            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1451              :                             // Set the tenant to Stopping to signal `set_stopping` that we're done.
    1452            0 :                             make_broken_or_stopping(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"));
    1453            0 :                             return Ok(());
    1454              :                         },
    1455              :                     )
    1456              :                 } else {
    1457              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1458              :                     // concurrent_tenant_warmup queue
    1459            0 :                     AttachType::Normal
    1460              :                 };
    1461              : 
    1462            0 :                 let preload = match &mode {
    1463              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1464            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1465            0 :                         let res = tenant_clone
    1466            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1467            0 :                             .await;
    1468            0 :                         match res {
    1469            0 :                             Ok(p) => Some(p),
    1470            0 :                             Err(e) => {
    1471            0 :                                 make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1472            0 :                                 return Ok(());
    1473              :                             }
    1474              :                         }
    1475              :                     }
    1476              : 
    1477              :                 };
    1478              : 
    1479              :                 // Remote preload is complete.
    1480            0 :                 drop(remote_load_completion);
    1481            0 : 
    1482            0 : 
    1483            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1484            0 :                 let attach_start = std::time::Instant::now();
    1485            0 :                 let attached = {
    1486            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1487            0 :                     tenant_clone.attach(preload, &ctx).await
    1488              :                 };
    1489            0 :                 let attach_duration = attach_start.elapsed();
    1490            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1491            0 : 
    1492            0 :                 match attached {
    1493              :                     Ok(()) => {
    1494            0 :                         info!("attach finished, activating");
    1495            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1496              :                     }
    1497            0 :                     Err(e) => make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e)),
    1498              :                 }
    1499              : 
    1500              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1501              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1502              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1503              :                 //
    1504              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1505              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1506              :                 // then warmup will wait for that before proceeding to the next tenant.
    1507            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1508            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1509            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1510            0 :                     while futs.next().await.is_some() {}
    1511            0 :                     tracing::info!("Warm-up complete");
    1512            0 :                 }
    1513              : 
    1514            0 :                 Ok(())
    1515            0 :             }
    1516            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1517              :         );
    1518            0 :         Ok(tenant)
    1519            0 :     }
    1520              : 
    1521              :     #[instrument(skip_all)]
    1522              :     pub(crate) async fn preload(
    1523              :         self: &Arc<Self>,
    1524              :         remote_storage: &GenericRemoteStorage,
    1525              :         cancel: CancellationToken,
    1526              :     ) -> anyhow::Result<TenantPreload> {
    1527              :         span::debug_assert_current_span_has_tenant_id();
    1528              :         // Get list of remote timelines
    1529              :         // download index files for every tenant timeline
    1530              :         info!("listing remote timelines");
    1531              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1532              :             remote_storage,
    1533              :             self.tenant_shard_id,
    1534              :             cancel.clone(),
    1535              :         )
    1536              :         .await?;
    1537              : 
    1538              :         let tenant_manifest = match download_tenant_manifest(
    1539              :             remote_storage,
    1540              :             &self.tenant_shard_id,
    1541              :             self.generation,
    1542              :             &cancel,
    1543              :         )
    1544              :         .await
    1545              :         {
    1546              :             Ok((tenant_manifest, _, _)) => Some(tenant_manifest),
    1547              :             Err(DownloadError::NotFound) => None,
    1548              :             Err(err) => return Err(err.into()),
    1549              :         };
    1550              : 
    1551              :         info!(
    1552              :             "found {} timelines ({} offloaded timelines)",
    1553              :             remote_timeline_ids.len(),
    1554              :             tenant_manifest
    1555              :                 .as_ref()
    1556           12 :                 .map(|m| m.offloaded_timelines.len())
    1557              :                 .unwrap_or(0)
    1558              :         );
    1559              : 
    1560              :         for k in other_keys {
    1561              :             warn!("Unexpected non timeline key {k}");
    1562              :         }
    1563              : 
    1564              :         // Avoid downloading IndexPart of offloaded timelines.
    1565              :         let mut offloaded_with_prefix = HashSet::new();
    1566              :         if let Some(tenant_manifest) = &tenant_manifest {
    1567              :             for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1568              :                 if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1569              :                     offloaded_with_prefix.insert(offloaded.timeline_id);
    1570              :                 } else {
    1571              :                     // We'll take care later of timelines in the manifest without a prefix
    1572              :                 }
    1573              :             }
    1574              :         }
    1575              : 
    1576              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1577              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1578              :         // will kick the secondary in any case and cause a download.
    1579              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1580              : 
    1581              :         let timelines = self
    1582              :             .load_timelines_metadata(
    1583              :                 remote_timeline_ids,
    1584              :                 remote_storage,
    1585              :                 maybe_heatmap_at,
    1586              :                 cancel,
    1587              :             )
    1588              :             .await?;
    1589              : 
    1590              :         Ok(TenantPreload {
    1591              :             tenant_manifest,
    1592              :             timelines: timelines
    1593              :                 .into_iter()
    1594           12 :                 .map(|(id, tl)| (id, Some(tl)))
    1595            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1596              :                 .collect(),
    1597              :         })
    1598              :     }
    1599              : 
    1600          464 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1601          464 :         if !self.conf.load_previous_heatmap {
    1602            0 :             return None;
    1603          464 :         }
    1604          464 : 
    1605          464 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1606          464 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1607            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1608            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1609            0 :                 Err(err) => {
    1610            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1611            0 :                     None
    1612              :                 }
    1613              :             },
    1614          464 :             Err(err) => match err.kind() {
    1615          464 :                 std::io::ErrorKind::NotFound => None,
    1616              :                 _ => {
    1617            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1618            0 :                     None
    1619              :                 }
    1620              :             },
    1621              :         }
    1622          464 :     }
    1623              : 
    1624              :     ///
    1625              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1626              :     ///
    1627              :     /// No background tasks are started as part of this routine.
    1628              :     ///
    1629          464 :     async fn attach(
    1630          464 :         self: &Arc<Tenant>,
    1631          464 :         preload: Option<TenantPreload>,
    1632          464 :         ctx: &RequestContext,
    1633          464 :     ) -> anyhow::Result<()> {
    1634          464 :         span::debug_assert_current_span_has_tenant_id();
    1635          464 : 
    1636          464 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1637              : 
    1638          464 :         let Some(preload) = preload else {
    1639            0 :             anyhow::bail!(
    1640            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1641            0 :             );
    1642              :         };
    1643              : 
    1644          464 :         let mut offloaded_timeline_ids = HashSet::new();
    1645          464 :         let mut offloaded_timelines_list = Vec::new();
    1646          464 :         if let Some(tenant_manifest) = &preload.tenant_manifest {
    1647           12 :             for timeline_manifest in tenant_manifest.offloaded_timelines.iter() {
    1648            0 :                 let timeline_id = timeline_manifest.timeline_id;
    1649            0 :                 let offloaded_timeline =
    1650            0 :                     OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1651            0 :                 offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1652            0 :                 offloaded_timeline_ids.insert(timeline_id);
    1653            0 :             }
    1654          452 :         }
    1655              :         // Complete deletions for offloaded timeline id's from manifest.
    1656              :         // The manifest will be uploaded later in this function.
    1657          464 :         offloaded_timelines_list
    1658          464 :             .retain(|(offloaded_id, offloaded)| {
    1659            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1660            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1661            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1662            0 :                 if delete {
    1663            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1664            0 :                     offloaded.defuse_for_tenant_drop();
    1665            0 :                 }
    1666            0 :                 !delete
    1667          464 :         });
    1668          464 : 
    1669          464 :         let mut timelines_to_resume_deletions = vec![];
    1670          464 : 
    1671          464 :         let mut remote_index_and_client = HashMap::new();
    1672          464 :         let mut timeline_ancestors = HashMap::new();
    1673          464 :         let mut existent_timelines = HashSet::new();
    1674          476 :         for (timeline_id, preload) in preload.timelines {
    1675           12 :             let Some(preload) = preload else { continue };
    1676              :             // This is an invariant of the `preload` function's API
    1677           12 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1678           12 :             let index_part = match preload.index_part {
    1679           12 :                 Ok(i) => {
    1680           12 :                     debug!("remote index part exists for timeline {timeline_id}");
    1681              :                     // We found index_part on the remote, this is the standard case.
    1682           12 :                     existent_timelines.insert(timeline_id);
    1683           12 :                     i
    1684              :                 }
    1685              :                 Err(DownloadError::NotFound) => {
    1686              :                     // There is no index_part on the remote. We only get here
    1687              :                     // if there is some prefix for the timeline in the remote storage.
    1688              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1689              :                     // remnant from a prior incomplete creation or deletion attempt.
    1690              :                     // Delete the local directory as the deciding criterion for a
    1691              :                     // timeline's existence is presence of index_part.
    1692            0 :                     info!(%timeline_id, "index_part not found on remote");
    1693            0 :                     continue;
    1694              :                 }
    1695            0 :                 Err(DownloadError::Fatal(why)) => {
    1696            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1697            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1698            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1699            0 :                     anyhow::bail!(why.to_string());
    1700              :                 }
    1701            0 :                 Err(e) => {
    1702            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1703            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1704            0 :                     // as it might be a temporary issue and we don't want to re-download
    1705            0 :                     // everything after it resolves.
    1706            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1707              : 
    1708            0 :                     existent_timelines.insert(timeline_id);
    1709            0 :                     continue;
    1710              :                 }
    1711              :             };
    1712           12 :             match index_part {
    1713           12 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1714           12 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1715           12 :                     remote_index_and_client.insert(
    1716           12 :                         timeline_id,
    1717           12 :                         (index_part, preload.client, preload.previous_heatmap),
    1718           12 :                     );
    1719           12 :                 }
    1720            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1721            0 :                     info!(
    1722            0 :                         "timeline {} is deleted, picking to resume deletion",
    1723              :                         timeline_id
    1724              :                     );
    1725            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1726              :                 }
    1727              :             }
    1728              :         }
    1729              : 
    1730          464 :         let mut gc_blocks = HashMap::new();
    1731              : 
    1732              :         // For every timeline, download the metadata file, scan the local directory,
    1733              :         // and build a layer map that contains an entry for each remote and local
    1734              :         // layer file.
    1735          464 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1736          476 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1737           12 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1738           12 :                 .remove(&timeline_id)
    1739           12 :                 .expect("just put it in above");
    1740              : 
    1741           12 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1742              :                 // could just filter these away, but it helps while testing
    1743            0 :                 anyhow::ensure!(
    1744            0 :                     !blocking.reasons.is_empty(),
    1745            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1746              :                 );
    1747            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1748            0 :                 assert!(prev.is_none());
    1749           12 :             }
    1750              : 
    1751              :             // TODO again handle early failure
    1752           12 :             let effect = self
    1753           12 :                 .load_remote_timeline(
    1754           12 :                     timeline_id,
    1755           12 :                     index_part,
    1756           12 :                     remote_metadata,
    1757           12 :                     previous_heatmap,
    1758           12 :                     self.get_timeline_resources_for(remote_client),
    1759           12 :                     LoadTimelineCause::Attach,
    1760           12 :                     ctx,
    1761           12 :                 )
    1762           12 :                 .await
    1763           12 :                 .with_context(|| {
    1764            0 :                     format!(
    1765            0 :                         "failed to load remote timeline {} for tenant {}",
    1766            0 :                         timeline_id, self.tenant_shard_id
    1767            0 :                     )
    1768           12 :                 })?;
    1769              : 
    1770           12 :             match effect {
    1771           12 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1772           12 :                     // activation happens later, on Tenant::activate
    1773           12 :                 }
    1774              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1775              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1776            0 :                         timeline,
    1777            0 :                         import_pgdata,
    1778            0 :                         guard,
    1779            0 :                     },
    1780            0 :                 ) => {
    1781            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1782            0 :                         timeline,
    1783            0 :                         import_pgdata,
    1784            0 :                         ActivateTimelineArgs::No,
    1785            0 :                         guard,
    1786            0 :                         ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    1787            0 :                     ));
    1788            0 :                 }
    1789              :             }
    1790              :         }
    1791              : 
    1792              :         // Walk through deleted timelines, resume deletion
    1793          464 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1794            0 :             remote_timeline_client
    1795            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1796            0 :                 .context("init queue stopped")
    1797            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1798              : 
    1799            0 :             DeleteTimelineFlow::resume_deletion(
    1800            0 :                 Arc::clone(self),
    1801            0 :                 timeline_id,
    1802            0 :                 &index_part.metadata,
    1803            0 :                 remote_timeline_client,
    1804            0 :                 ctx,
    1805            0 :             )
    1806            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1807            0 :             .await
    1808            0 :             .context("resume_deletion")
    1809            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1810              :         }
    1811          464 :         {
    1812          464 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1813          464 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1814          464 :         }
    1815              : 
    1816              :         // Stash the preloaded tenant manifest, and upload a new manifest if changed.
    1817              :         //
    1818              :         // NB: this must happen after the tenant is fully populated above. In particular the
    1819              :         // offloaded timelines, which are included in the manifest.
    1820              :         {
    1821          464 :             let mut guard = self.remote_tenant_manifest.lock().await;
    1822          464 :             assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
    1823          464 :             *guard = preload.tenant_manifest;
    1824          464 :         }
    1825          464 :         self.maybe_upload_tenant_manifest().await?;
    1826              : 
    1827              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1828              :         // IndexPart is the source of truth.
    1829          464 :         self.clean_up_timelines(&existent_timelines)?;
    1830              : 
    1831          464 :         self.gc_block.set_scanned(gc_blocks);
    1832          464 : 
    1833          464 :         fail::fail_point!("attach-before-activate", |_| {
    1834            0 :             anyhow::bail!("attach-before-activate");
    1835          464 :         });
    1836          464 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1837              : 
    1838          464 :         info!("Done");
    1839              : 
    1840          464 :         Ok(())
    1841          464 :     }
    1842              : 
    1843              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1844              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1845              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1846          464 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1847          464 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1848              : 
    1849          464 :         let entries = match timelines_dir.read_dir_utf8() {
    1850          464 :             Ok(d) => d,
    1851            0 :             Err(e) => {
    1852            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1853            0 :                     return Ok(());
    1854              :                 } else {
    1855            0 :                     return Err(e).context("list timelines directory for tenant");
    1856              :                 }
    1857              :             }
    1858              :         };
    1859              : 
    1860          480 :         for entry in entries {
    1861           16 :             let entry = entry.context("read timeline dir entry")?;
    1862           16 :             let entry_path = entry.path();
    1863              : 
    1864           16 :             let purge = if crate::is_temporary(entry_path) {
    1865            0 :                 true
    1866              :             } else {
    1867           16 :                 match TimelineId::try_from(entry_path.file_name()) {
    1868           16 :                     Ok(i) => {
    1869           16 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1870           16 :                         !existent_timelines.contains(&i)
    1871              :                     }
    1872            0 :                     Err(e) => {
    1873            0 :                         tracing::warn!(
    1874            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1875              :                         );
    1876              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1877            0 :                         false
    1878              :                     }
    1879              :                 }
    1880              :             };
    1881              : 
    1882           16 :             if purge {
    1883            4 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1884            4 :                 if let Err(e) = match entry.file_type() {
    1885            4 :                     Ok(t) => if t.is_dir() {
    1886            4 :                         std::fs::remove_dir_all(entry_path)
    1887              :                     } else {
    1888            0 :                         std::fs::remove_file(entry_path)
    1889              :                     }
    1890            4 :                     .or_else(fs_ext::ignore_not_found),
    1891            0 :                     Err(e) => Err(e),
    1892              :                 } {
    1893            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1894            4 :                 }
    1895           12 :             }
    1896              :         }
    1897              : 
    1898          464 :         Ok(())
    1899          464 :     }
    1900              : 
    1901              :     /// Get sum of all remote timelines sizes
    1902              :     ///
    1903              :     /// This function relies on the index_part instead of listing the remote storage
    1904            0 :     pub fn remote_size(&self) -> u64 {
    1905            0 :         let mut size = 0;
    1906              : 
    1907            0 :         for timeline in self.list_timelines() {
    1908            0 :             size += timeline.remote_client.get_remote_physical_size();
    1909            0 :         }
    1910              : 
    1911            0 :         size
    1912            0 :     }
    1913              : 
    1914              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1915              :     #[allow(clippy::too_many_arguments)]
    1916              :     async fn load_remote_timeline(
    1917              :         self: &Arc<Self>,
    1918              :         timeline_id: TimelineId,
    1919              :         index_part: IndexPart,
    1920              :         remote_metadata: TimelineMetadata,
    1921              :         previous_heatmap: Option<PreviousHeatmap>,
    1922              :         resources: TimelineResources,
    1923              :         cause: LoadTimelineCause,
    1924              :         ctx: &RequestContext,
    1925              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1926              :         span::debug_assert_current_span_has_tenant_id();
    1927              : 
    1928              :         info!("downloading index file for timeline {}", timeline_id);
    1929              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1930              :             .await
    1931              :             .context("Failed to create new timeline directory")?;
    1932              : 
    1933              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1934              :             let timelines = self.timelines.lock().unwrap();
    1935              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1936            0 :                 || {
    1937            0 :                     anyhow::anyhow!(
    1938            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1939            0 :                     )
    1940            0 :                 },
    1941              :             )?))
    1942              :         } else {
    1943              :             None
    1944              :         };
    1945              : 
    1946              :         self.timeline_init_and_sync(
    1947              :             timeline_id,
    1948              :             resources,
    1949              :             index_part,
    1950              :             remote_metadata,
    1951              :             previous_heatmap,
    1952              :             ancestor,
    1953              :             cause,
    1954              :             ctx,
    1955              :         )
    1956              :         .await
    1957              :     }
    1958              : 
    1959          464 :     async fn load_timelines_metadata(
    1960          464 :         self: &Arc<Tenant>,
    1961          464 :         timeline_ids: HashSet<TimelineId>,
    1962          464 :         remote_storage: &GenericRemoteStorage,
    1963          464 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    1964          464 :         cancel: CancellationToken,
    1965          464 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1966          464 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    1967          464 : 
    1968          464 :         let mut part_downloads = JoinSet::new();
    1969          476 :         for timeline_id in timeline_ids {
    1970           12 :             let cancel_clone = cancel.clone();
    1971           12 : 
    1972           12 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    1973            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    1974            0 :                     heatmap: h,
    1975            0 :                     read_at: hs.1,
    1976            0 :                     end_lsn: None,
    1977            0 :                 })
    1978           12 :             });
    1979           12 :             part_downloads.spawn(
    1980           12 :                 self.load_timeline_metadata(
    1981           12 :                     timeline_id,
    1982           12 :                     remote_storage.clone(),
    1983           12 :                     previous_timeline_heatmap,
    1984           12 :                     cancel_clone,
    1985           12 :                 )
    1986           12 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    1987              :             );
    1988              :         }
    1989              : 
    1990          464 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1991              : 
    1992              :         loop {
    1993          476 :             tokio::select!(
    1994          476 :                 next = part_downloads.join_next() => {
    1995          476 :                     match next {
    1996           12 :                         Some(result) => {
    1997           12 :                             let preload = result.context("join preload task")?;
    1998           12 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1999              :                         },
    2000              :                         None => {
    2001          464 :                             break;
    2002              :                         }
    2003              :                     }
    2004              :                 },
    2005          476 :                 _ = cancel.cancelled() => {
    2006            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    2007              :                 }
    2008              :             )
    2009              :         }
    2010              : 
    2011          464 :         Ok(timeline_preloads)
    2012          464 :     }
    2013              : 
    2014           12 :     fn build_timeline_client(
    2015           12 :         &self,
    2016           12 :         timeline_id: TimelineId,
    2017           12 :         remote_storage: GenericRemoteStorage,
    2018           12 :     ) -> RemoteTimelineClient {
    2019           12 :         RemoteTimelineClient::new(
    2020           12 :             remote_storage.clone(),
    2021           12 :             self.deletion_queue_client.clone(),
    2022           12 :             self.conf,
    2023           12 :             self.tenant_shard_id,
    2024           12 :             timeline_id,
    2025           12 :             self.generation,
    2026           12 :             &self.tenant_conf.load().location,
    2027           12 :         )
    2028           12 :     }
    2029              : 
    2030           12 :     fn load_timeline_metadata(
    2031           12 :         self: &Arc<Tenant>,
    2032           12 :         timeline_id: TimelineId,
    2033           12 :         remote_storage: GenericRemoteStorage,
    2034           12 :         previous_heatmap: Option<PreviousHeatmap>,
    2035           12 :         cancel: CancellationToken,
    2036           12 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2037           12 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2038           12 :         async move {
    2039           12 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2040           12 :             debug!("starting index part download");
    2041              : 
    2042           12 :             let index_part = client.download_index_file(&cancel).await;
    2043              : 
    2044           12 :             debug!("finished index part download");
    2045              : 
    2046           12 :             TimelinePreload {
    2047           12 :                 client,
    2048           12 :                 timeline_id,
    2049           12 :                 index_part,
    2050           12 :                 previous_heatmap,
    2051           12 :             }
    2052           12 :         }
    2053           12 :     }
    2054              : 
    2055            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2056            0 :         timeline_id: TimelineId,
    2057            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2058            0 :     ) -> Result<(), TimelineArchivalError> {
    2059            0 :         let children: Vec<TimelineId> = timelines
    2060            0 :             .iter()
    2061            0 :             .filter_map(|(id, entry)| {
    2062            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2063            0 :                     return None;
    2064            0 :                 }
    2065            0 :                 if entry.is_archived() == Some(true) {
    2066            0 :                     return None;
    2067            0 :                 }
    2068            0 :                 Some(*id)
    2069            0 :             })
    2070            0 :             .collect();
    2071            0 : 
    2072            0 :         if !children.is_empty() {
    2073            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2074            0 :         }
    2075            0 :         Ok(())
    2076            0 :     }
    2077              : 
    2078            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2079            0 :         ancestor_timeline_id: TimelineId,
    2080            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2081            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2082            0 :             '_,
    2083            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2084            0 :         >,
    2085            0 :     ) -> Result<(), TimelineArchivalError> {
    2086            0 :         let has_archived_parent =
    2087            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2088            0 :                 ancestor_timeline.is_archived() == Some(true)
    2089            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2090            0 :                 true
    2091              :             } else {
    2092            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2093            0 :                 if cfg!(debug_assertions) {
    2094            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2095            0 :                 }
    2096            0 :                 return Err(TimelineArchivalError::NotFound);
    2097              :             };
    2098            0 :         if has_archived_parent {
    2099            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2100            0 :                 ancestor_timeline_id,
    2101            0 :             ));
    2102            0 :         }
    2103            0 :         Ok(())
    2104            0 :     }
    2105              : 
    2106            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2107            0 :         timeline: &Arc<Timeline>,
    2108            0 :     ) -> Result<(), TimelineArchivalError> {
    2109            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2110            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2111            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2112            0 :                     ancestor_timeline.timeline_id,
    2113            0 :                 ));
    2114            0 :             }
    2115            0 :         }
    2116            0 :         Ok(())
    2117            0 :     }
    2118              : 
    2119              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2120              :     ///
    2121              :     /// Counterpart to [`offload_timeline`].
    2122            0 :     async fn unoffload_timeline(
    2123            0 :         self: &Arc<Self>,
    2124            0 :         timeline_id: TimelineId,
    2125            0 :         broker_client: storage_broker::BrokerClientChannel,
    2126            0 :         ctx: RequestContext,
    2127            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2128            0 :         info!("unoffloading timeline");
    2129              : 
    2130              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2131              :         // We expect callers of this function to ensure this.
    2132            0 :         match self.current_state() {
    2133              :             TenantState::Activating { .. }
    2134              :             | TenantState::Attaching
    2135              :             | TenantState::Broken { .. } => {
    2136            0 :                 panic!("Timeline expected to be active")
    2137              :             }
    2138            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2139            0 :             TenantState::Active => {}
    2140            0 :         }
    2141            0 :         let cancel = self.cancel.clone();
    2142            0 : 
    2143            0 :         // Protect against concurrent attempts to use this TimelineId
    2144            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2145            0 :         let allow_offloaded = true;
    2146            0 :         let _create_guard = self
    2147            0 :             .create_timeline_create_guard(
    2148            0 :                 timeline_id,
    2149            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2150            0 :                 allow_offloaded,
    2151            0 :             )
    2152            0 :             .map_err(|err| match err {
    2153            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2154              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2155            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2156              :                 }
    2157            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2158            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2159            0 :             })?;
    2160              : 
    2161            0 :         let timeline_preload = self
    2162            0 :             .load_timeline_metadata(
    2163            0 :                 timeline_id,
    2164            0 :                 self.remote_storage.clone(),
    2165            0 :                 None,
    2166            0 :                 cancel.clone(),
    2167            0 :             )
    2168            0 :             .await;
    2169              : 
    2170            0 :         let index_part = match timeline_preload.index_part {
    2171            0 :             Ok(index_part) => {
    2172            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2173            0 :                 index_part
    2174              :             }
    2175              :             Err(DownloadError::NotFound) => {
    2176            0 :                 error!(%timeline_id, "index_part not found on remote");
    2177            0 :                 return Err(TimelineArchivalError::NotFound);
    2178              :             }
    2179            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2180            0 :             Err(e) => {
    2181            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2182            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2183            0 :                 return Err(TimelineArchivalError::Other(
    2184            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2185            0 :                 ));
    2186              :             }
    2187              :         };
    2188            0 :         let index_part = match index_part {
    2189            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2190            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2191            0 :                 info!("timeline is deleted according to index_part.json");
    2192            0 :                 return Err(TimelineArchivalError::NotFound);
    2193              :             }
    2194              :         };
    2195            0 :         let remote_metadata = index_part.metadata.clone();
    2196            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2197            0 :         self.load_remote_timeline(
    2198            0 :             timeline_id,
    2199            0 :             index_part,
    2200            0 :             remote_metadata,
    2201            0 :             None,
    2202            0 :             timeline_resources,
    2203            0 :             LoadTimelineCause::Unoffload,
    2204            0 :             &ctx,
    2205            0 :         )
    2206            0 :         .await
    2207            0 :         .with_context(|| {
    2208            0 :             format!(
    2209            0 :                 "failed to load remote timeline {} for tenant {}",
    2210            0 :                 timeline_id, self.tenant_shard_id
    2211            0 :             )
    2212            0 :         })
    2213            0 :         .map_err(TimelineArchivalError::Other)?;
    2214              : 
    2215            0 :         let timeline = {
    2216            0 :             let timelines = self.timelines.lock().unwrap();
    2217            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2218            0 :                 warn!("timeline not available directly after attach");
    2219              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2220              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2221            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2222            0 :                     "timeline not available directly after attach"
    2223            0 :                 )));
    2224              :             };
    2225            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2226            0 :             match offloaded_timelines.remove(&timeline_id) {
    2227            0 :                 Some(offloaded) => {
    2228            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2229            0 :                 }
    2230            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2231              :             }
    2232              : 
    2233            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2234            0 : 
    2235            0 :             Arc::clone(timeline)
    2236            0 :         };
    2237            0 : 
    2238            0 :         // Upload new list of offloaded timelines to S3
    2239            0 :         self.maybe_upload_tenant_manifest().await?;
    2240              : 
    2241              :         // Activate the timeline (if it makes sense)
    2242            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2243            0 :             let background_jobs_can_start = None;
    2244            0 :             timeline.activate(
    2245            0 :                 self.clone(),
    2246            0 :                 broker_client.clone(),
    2247            0 :                 background_jobs_can_start,
    2248            0 :                 &ctx.with_scope_timeline(&timeline),
    2249            0 :             );
    2250            0 :         }
    2251              : 
    2252            0 :         info!("timeline unoffloading complete");
    2253            0 :         Ok(timeline)
    2254            0 :     }
    2255              : 
    2256            0 :     pub(crate) async fn apply_timeline_archival_config(
    2257            0 :         self: &Arc<Self>,
    2258            0 :         timeline_id: TimelineId,
    2259            0 :         new_state: TimelineArchivalState,
    2260            0 :         broker_client: storage_broker::BrokerClientChannel,
    2261            0 :         ctx: RequestContext,
    2262            0 :     ) -> Result<(), TimelineArchivalError> {
    2263            0 :         info!("setting timeline archival config");
    2264              :         // First part: figure out what is needed to do, and do validation
    2265            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2266            0 :             let timelines = self.timelines.lock().unwrap();
    2267              : 
    2268            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2269            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2270            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2271            0 :                     return Err(TimelineArchivalError::NotFound);
    2272              :                 };
    2273            0 :                 if new_state == TimelineArchivalState::Archived {
    2274              :                     // It's offloaded already, so nothing to do
    2275            0 :                     return Ok(());
    2276            0 :                 }
    2277            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2278            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2279            0 :                         ancestor_timeline_id,
    2280            0 :                         &timelines,
    2281            0 :                         &offloaded_timelines,
    2282            0 :                     )?;
    2283            0 :                 }
    2284            0 :                 break 'outer None;
    2285              :             };
    2286              : 
    2287              :             // Do some validation. We release the timelines lock below, so there is potential
    2288              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2289              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2290            0 :             match new_state {
    2291              :                 TimelineArchivalState::Unarchived => {
    2292            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2293              :                 }
    2294              :                 TimelineArchivalState::Archived => {
    2295            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2296              :                 }
    2297              :             }
    2298            0 :             Some(Arc::clone(timeline))
    2299              :         };
    2300              : 
    2301              :         // Second part: unoffload timeline (if needed)
    2302            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2303            0 :             timeline
    2304              :         } else {
    2305              :             // Turn offloaded timeline into a non-offloaded one
    2306            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2307            0 :                 .await?
    2308              :         };
    2309              : 
    2310              :         // Third part: upload new timeline archival state and block until it is present in S3
    2311            0 :         let upload_needed = match timeline
    2312            0 :             .remote_client
    2313            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2314              :         {
    2315            0 :             Ok(upload_needed) => upload_needed,
    2316            0 :             Err(e) => {
    2317            0 :                 if timeline.cancel.is_cancelled() {
    2318            0 :                     return Err(TimelineArchivalError::Cancelled);
    2319              :                 } else {
    2320            0 :                     return Err(TimelineArchivalError::Other(e));
    2321              :                 }
    2322              :             }
    2323              :         };
    2324              : 
    2325            0 :         if upload_needed {
    2326            0 :             info!("Uploading new state");
    2327              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2328            0 :             let Ok(v) =
    2329            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2330              :             else {
    2331            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2332            0 :                 return Err(TimelineArchivalError::Timeout);
    2333              :             };
    2334            0 :             v.map_err(|e| match e {
    2335            0 :                 WaitCompletionError::NotInitialized(e) => {
    2336            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2337              :                 }
    2338              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2339            0 :                     TimelineArchivalError::Cancelled
    2340              :                 }
    2341            0 :             })?;
    2342            0 :         }
    2343            0 :         Ok(())
    2344            0 :     }
    2345              : 
    2346            4 :     pub fn get_offloaded_timeline(
    2347            4 :         &self,
    2348            4 :         timeline_id: TimelineId,
    2349            4 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2350            4 :         self.timelines_offloaded
    2351            4 :             .lock()
    2352            4 :             .unwrap()
    2353            4 :             .get(&timeline_id)
    2354            4 :             .map(Arc::clone)
    2355            4 :             .ok_or(GetTimelineError::NotFound {
    2356            4 :                 tenant_id: self.tenant_shard_id,
    2357            4 :                 timeline_id,
    2358            4 :             })
    2359            4 :     }
    2360              : 
    2361            8 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2362            8 :         self.tenant_shard_id
    2363            8 :     }
    2364              : 
    2365              :     /// Get Timeline handle for given Neon timeline ID.
    2366              :     /// This function is idempotent. It doesn't change internal state in any way.
    2367          444 :     pub fn get_timeline(
    2368          444 :         &self,
    2369          444 :         timeline_id: TimelineId,
    2370          444 :         active_only: bool,
    2371          444 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2372          444 :         let timelines_accessor = self.timelines.lock().unwrap();
    2373          444 :         let timeline = timelines_accessor
    2374          444 :             .get(&timeline_id)
    2375          444 :             .ok_or(GetTimelineError::NotFound {
    2376          444 :                 tenant_id: self.tenant_shard_id,
    2377          444 :                 timeline_id,
    2378          444 :             })?;
    2379              : 
    2380          440 :         if active_only && !timeline.is_active() {
    2381            0 :             Err(GetTimelineError::NotActive {
    2382            0 :                 tenant_id: self.tenant_shard_id,
    2383            0 :                 timeline_id,
    2384            0 :                 state: timeline.current_state(),
    2385            0 :             })
    2386              :         } else {
    2387          440 :             Ok(Arc::clone(timeline))
    2388              :         }
    2389          444 :     }
    2390              : 
    2391              :     /// Lists timelines the tenant contains.
    2392              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2393            8 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2394            8 :         self.timelines
    2395            8 :             .lock()
    2396            8 :             .unwrap()
    2397            8 :             .values()
    2398            8 :             .map(Arc::clone)
    2399            8 :             .collect()
    2400            8 :     }
    2401              : 
    2402              :     /// Lists timelines the tenant manages, including offloaded ones.
    2403              :     ///
    2404              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2405            0 :     pub fn list_timelines_and_offloaded(
    2406            0 :         &self,
    2407            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2408            0 :         let timelines = self
    2409            0 :             .timelines
    2410            0 :             .lock()
    2411            0 :             .unwrap()
    2412            0 :             .values()
    2413            0 :             .map(Arc::clone)
    2414            0 :             .collect();
    2415            0 :         let offloaded = self
    2416            0 :             .timelines_offloaded
    2417            0 :             .lock()
    2418            0 :             .unwrap()
    2419            0 :             .values()
    2420            0 :             .map(Arc::clone)
    2421            0 :             .collect();
    2422            0 :         (timelines, offloaded)
    2423            0 :     }
    2424              : 
    2425            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2426            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2427            0 :     }
    2428              : 
    2429              :     /// This is used by tests & import-from-basebackup.
    2430              :     ///
    2431              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2432              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2433              :     ///
    2434              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2435              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2436              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2437              :     /// to the [`Tenant::timelines`].
    2438              :     ///
    2439              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2440          448 :     pub(crate) async fn create_empty_timeline(
    2441          448 :         self: &Arc<Self>,
    2442          448 :         new_timeline_id: TimelineId,
    2443          448 :         initdb_lsn: Lsn,
    2444          448 :         pg_version: u32,
    2445          448 :         ctx: &RequestContext,
    2446          448 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2447          448 :         anyhow::ensure!(
    2448          448 :             self.is_active(),
    2449            0 :             "Cannot create empty timelines on inactive tenant"
    2450              :         );
    2451              : 
    2452              :         // Protect against concurrent attempts to use this TimelineId
    2453          448 :         let create_guard = match self
    2454          448 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2455          448 :             .await?
    2456              :         {
    2457          444 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2458              :             StartCreatingTimelineResult::Idempotent(_) => {
    2459            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2460              :             }
    2461              :         };
    2462              : 
    2463          444 :         let new_metadata = TimelineMetadata::new(
    2464          444 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2465          444 :             // make it valid, before calling finish_creation()
    2466          444 :             Lsn(0),
    2467          444 :             None,
    2468          444 :             None,
    2469          444 :             Lsn(0),
    2470          444 :             initdb_lsn,
    2471          444 :             initdb_lsn,
    2472          444 :             pg_version,
    2473          444 :         );
    2474          444 :         self.prepare_new_timeline(
    2475          444 :             new_timeline_id,
    2476          444 :             &new_metadata,
    2477          444 :             create_guard,
    2478          444 :             initdb_lsn,
    2479          444 :             None,
    2480          444 :             None,
    2481          444 :             ctx,
    2482          444 :         )
    2483          444 :         .await
    2484          448 :     }
    2485              : 
    2486              :     /// Helper for unit tests to create an empty timeline.
    2487              :     ///
    2488              :     /// The timeline is has state value `Active` but its background loops are not running.
    2489              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2490              :     // Our current tests don't need the background loops.
    2491              :     #[cfg(test)]
    2492          428 :     pub async fn create_test_timeline(
    2493          428 :         self: &Arc<Self>,
    2494          428 :         new_timeline_id: TimelineId,
    2495          428 :         initdb_lsn: Lsn,
    2496          428 :         pg_version: u32,
    2497          428 :         ctx: &RequestContext,
    2498          428 :     ) -> anyhow::Result<Arc<Timeline>> {
    2499          428 :         let (uninit_tl, ctx) = self
    2500          428 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2501          428 :             .await?;
    2502          428 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2503          428 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2504              : 
    2505              :         // Setup minimum keys required for the timeline to be usable.
    2506          428 :         let mut modification = tline.begin_modification(initdb_lsn);
    2507          428 :         modification
    2508          428 :             .init_empty_test_timeline()
    2509          428 :             .context("init_empty_test_timeline")?;
    2510          428 :         modification
    2511          428 :             .commit(&ctx)
    2512          428 :             .await
    2513          428 :             .context("commit init_empty_test_timeline modification")?;
    2514              : 
    2515              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2516          428 :         tline.maybe_spawn_flush_loop();
    2517          428 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2518              : 
    2519              :         // Make sure the freeze_and_flush reaches remote storage.
    2520          428 :         tline.remote_client.wait_completion().await.unwrap();
    2521              : 
    2522          428 :         let tl = uninit_tl.finish_creation().await?;
    2523              :         // The non-test code would call tl.activate() here.
    2524          428 :         tl.set_state(TimelineState::Active);
    2525          428 :         Ok(tl)
    2526          428 :     }
    2527              : 
    2528              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2529              :     #[cfg(test)]
    2530              :     #[allow(clippy::too_many_arguments)]
    2531           96 :     pub async fn create_test_timeline_with_layers(
    2532           96 :         self: &Arc<Self>,
    2533           96 :         new_timeline_id: TimelineId,
    2534           96 :         initdb_lsn: Lsn,
    2535           96 :         pg_version: u32,
    2536           96 :         ctx: &RequestContext,
    2537           96 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2538           96 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2539           96 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2540           96 :         end_lsn: Lsn,
    2541           96 :     ) -> anyhow::Result<Arc<Timeline>> {
    2542              :         use checks::check_valid_layermap;
    2543              :         use itertools::Itertools;
    2544              : 
    2545           96 :         let tline = self
    2546           96 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2547           96 :             .await?;
    2548           96 :         tline.force_advance_lsn(end_lsn);
    2549          284 :         for deltas in delta_layer_desc {
    2550          188 :             tline
    2551          188 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2552          188 :                 .await?;
    2553              :         }
    2554          232 :         for (lsn, images) in image_layer_desc {
    2555          136 :             tline
    2556          136 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2557          136 :                 .await?;
    2558              :         }
    2559          112 :         for in_memory in in_memory_layer_desc {
    2560           16 :             tline
    2561           16 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2562           16 :                 .await?;
    2563              :         }
    2564           96 :         let layer_names = tline
    2565           96 :             .layers
    2566           96 :             .read()
    2567           96 :             .await
    2568           96 :             .layer_map()
    2569           96 :             .unwrap()
    2570           96 :             .iter_historic_layers()
    2571          420 :             .map(|layer| layer.layer_name())
    2572           96 :             .collect_vec();
    2573           96 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2574            0 :             bail!("invalid layermap: {err}");
    2575           96 :         }
    2576           96 :         Ok(tline)
    2577           96 :     }
    2578              : 
    2579              :     /// Create a new timeline.
    2580              :     ///
    2581              :     /// Returns the new timeline ID and reference to its Timeline object.
    2582              :     ///
    2583              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2584              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2585              :     #[allow(clippy::too_many_arguments)]
    2586            0 :     pub(crate) async fn create_timeline(
    2587            0 :         self: &Arc<Tenant>,
    2588            0 :         params: CreateTimelineParams,
    2589            0 :         broker_client: storage_broker::BrokerClientChannel,
    2590            0 :         ctx: &RequestContext,
    2591            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2592            0 :         if !self.is_active() {
    2593            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2594            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2595              :             } else {
    2596            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2597            0 :                     "Cannot create timelines on inactive tenant"
    2598            0 :                 )));
    2599              :             }
    2600            0 :         }
    2601              : 
    2602            0 :         let _gate = self
    2603            0 :             .gate
    2604            0 :             .enter()
    2605            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2606              : 
    2607            0 :         let result: CreateTimelineResult = match params {
    2608              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2609            0 :                 new_timeline_id,
    2610            0 :                 existing_initdb_timeline_id,
    2611            0 :                 pg_version,
    2612            0 :             }) => {
    2613            0 :                 self.bootstrap_timeline(
    2614            0 :                     new_timeline_id,
    2615            0 :                     pg_version,
    2616            0 :                     existing_initdb_timeline_id,
    2617            0 :                     ctx,
    2618            0 :                 )
    2619            0 :                 .await?
    2620              :             }
    2621              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2622            0 :                 new_timeline_id,
    2623            0 :                 ancestor_timeline_id,
    2624            0 :                 mut ancestor_start_lsn,
    2625              :             }) => {
    2626            0 :                 let ancestor_timeline = self
    2627            0 :                     .get_timeline(ancestor_timeline_id, false)
    2628            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2629              : 
    2630              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2631              :                 // ready for other purposes either.
    2632            0 :                 if !ancestor_timeline.is_active() {
    2633            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2634            0 :                 }
    2635            0 : 
    2636            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2637            0 :                     info!("tried to branch archived timeline");
    2638            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2639            0 :                 }
    2640              : 
    2641            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2642            0 :                     *lsn = lsn.align();
    2643            0 : 
    2644            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2645            0 :                     if ancestor_ancestor_lsn > *lsn {
    2646              :                         // can we safely just branch from the ancestor instead?
    2647            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2648            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2649            0 :                             lsn,
    2650            0 :                             ancestor_timeline_id,
    2651            0 :                             ancestor_ancestor_lsn,
    2652            0 :                         )));
    2653            0 :                     }
    2654            0 : 
    2655            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2656            0 :                     // to the requested branch point. The repository code itself doesn't
    2657            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2658            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2659            0 :                     // sizes etc. and that would get confused if the previous page versions
    2660            0 :                     // are not in the repository yet.
    2661            0 :                     ancestor_timeline
    2662            0 :                         .wait_lsn(
    2663            0 :                             *lsn,
    2664            0 :                             timeline::WaitLsnWaiter::Tenant,
    2665            0 :                             timeline::WaitLsnTimeout::Default,
    2666            0 :                             ctx,
    2667            0 :                         )
    2668            0 :                         .await
    2669            0 :                         .map_err(|e| match e {
    2670            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2671            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2672              :                             }
    2673            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2674            0 :                         })?;
    2675            0 :                 }
    2676              : 
    2677            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2678            0 :                     .await?
    2679              :             }
    2680            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2681            0 :                 self.create_timeline_import_pgdata(
    2682            0 :                     params,
    2683            0 :                     ActivateTimelineArgs::Yes {
    2684            0 :                         broker_client: broker_client.clone(),
    2685            0 :                     },
    2686            0 :                     ctx,
    2687            0 :                 )
    2688            0 :                 .await?
    2689              :             }
    2690              :         };
    2691              : 
    2692              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2693              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2694              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2695              :         //
    2696              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2697              :         // assume that, because they can see the timeline via API, that the creation is done and
    2698              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2699              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2700              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2701              :         //
    2702              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2703              :         // creation API until it returns success. Only then is durability guaranteed.
    2704            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2705            0 :         result
    2706            0 :             .timeline()
    2707            0 :             .remote_client
    2708            0 :             .wait_completion()
    2709            0 :             .await
    2710            0 :             .map_err(|e| match e {
    2711              :                 WaitCompletionError::NotInitialized(
    2712            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2713            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2714              :                 WaitCompletionError::NotInitialized(_) => {
    2715              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2716            0 :                     debug_assert!(false);
    2717            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2718              :                 }
    2719              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2720            0 :                     CreateTimelineError::ShuttingDown
    2721              :                 }
    2722            0 :             })?;
    2723              : 
    2724              :         // The creating task is responsible for activating the timeline.
    2725              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2726              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2727            0 :         let activated_timeline = match result {
    2728            0 :             CreateTimelineResult::Created(timeline) => {
    2729            0 :                 timeline.activate(
    2730            0 :                     self.clone(),
    2731            0 :                     broker_client,
    2732            0 :                     None,
    2733            0 :                     &ctx.with_scope_timeline(&timeline),
    2734            0 :                 );
    2735            0 :                 timeline
    2736              :             }
    2737            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2738            0 :                 info!(
    2739            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2740              :                 );
    2741            0 :                 timeline
    2742              :             }
    2743            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2744            0 :                 info!(
    2745            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2746              :                 );
    2747            0 :                 timeline
    2748              :             }
    2749              :         };
    2750              : 
    2751            0 :         Ok(activated_timeline)
    2752            0 :     }
    2753              : 
    2754              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2755              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2756              :     /// [`Tenant::timelines`] map when the import completes.
    2757              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2758              :     /// for the response.
    2759            0 :     async fn create_timeline_import_pgdata(
    2760            0 :         self: &Arc<Tenant>,
    2761            0 :         params: CreateTimelineParamsImportPgdata,
    2762            0 :         activate: ActivateTimelineArgs,
    2763            0 :         ctx: &RequestContext,
    2764            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2765            0 :         let CreateTimelineParamsImportPgdata {
    2766            0 :             new_timeline_id,
    2767            0 :             location,
    2768            0 :             idempotency_key,
    2769            0 :         } = params;
    2770            0 : 
    2771            0 :         let started_at = chrono::Utc::now().naive_utc();
    2772              : 
    2773              :         //
    2774              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2775              :         // is the canonical way we do it.
    2776              :         // - create an empty timeline in-memory
    2777              :         // - use its remote_timeline_client to do the upload
    2778              :         // - dispose of the uninit timeline
    2779              :         // - keep the creation guard alive
    2780              : 
    2781            0 :         let timeline_create_guard = match self
    2782            0 :             .start_creating_timeline(
    2783            0 :                 new_timeline_id,
    2784            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2785            0 :                     idempotency_key: idempotency_key.clone(),
    2786            0 :                 }),
    2787            0 :             )
    2788            0 :             .await?
    2789              :         {
    2790            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2791            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2792            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2793              :             }
    2794              :         };
    2795              : 
    2796            0 :         let (mut uninit_timeline, timeline_ctx) = {
    2797            0 :             let this = &self;
    2798            0 :             let initdb_lsn = Lsn(0);
    2799            0 :             async move {
    2800            0 :                 let new_metadata = TimelineMetadata::new(
    2801            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2802            0 :                     // make it valid, before calling finish_creation()
    2803            0 :                     Lsn(0),
    2804            0 :                     None,
    2805            0 :                     None,
    2806            0 :                     Lsn(0),
    2807            0 :                     initdb_lsn,
    2808            0 :                     initdb_lsn,
    2809            0 :                     15,
    2810            0 :                 );
    2811            0 :                 this.prepare_new_timeline(
    2812            0 :                     new_timeline_id,
    2813            0 :                     &new_metadata,
    2814            0 :                     timeline_create_guard,
    2815            0 :                     initdb_lsn,
    2816            0 :                     None,
    2817            0 :                     None,
    2818            0 :                     ctx,
    2819            0 :                 )
    2820            0 :                 .await
    2821            0 :             }
    2822            0 :         }
    2823            0 :         .await?;
    2824              : 
    2825            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2826            0 :             idempotency_key,
    2827            0 :             location,
    2828            0 :             started_at,
    2829            0 :         };
    2830            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2831            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2832            0 :         );
    2833            0 :         uninit_timeline
    2834            0 :             .raw_timeline()
    2835            0 :             .unwrap()
    2836            0 :             .remote_client
    2837            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2838              : 
    2839              :         // wait_completion happens in caller
    2840              : 
    2841            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2842            0 : 
    2843            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2844            0 :             timeline.clone(),
    2845            0 :             index_part,
    2846            0 :             activate,
    2847            0 :             timeline_create_guard,
    2848            0 :             timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    2849            0 :         ));
    2850            0 : 
    2851            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2852            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2853            0 :     }
    2854              : 
    2855              :     #[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))]
    2856              :     async fn create_timeline_import_pgdata_task(
    2857              :         self: Arc<Tenant>,
    2858              :         timeline: Arc<Timeline>,
    2859              :         index_part: import_pgdata::index_part_format::Root,
    2860              :         activate: ActivateTimelineArgs,
    2861              :         timeline_create_guard: TimelineCreateGuard,
    2862              :         ctx: RequestContext,
    2863              :     ) {
    2864              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2865              :         info!("starting");
    2866              :         scopeguard::defer! {info!("exiting")};
    2867              : 
    2868              :         let res = self
    2869              :             .create_timeline_import_pgdata_task_impl(
    2870              :                 timeline,
    2871              :                 index_part,
    2872              :                 activate,
    2873              :                 timeline_create_guard,
    2874              :                 ctx,
    2875              :             )
    2876              :             .await;
    2877              :         if let Err(err) = &res {
    2878              :             error!(?err, "task failed");
    2879              :             // TODO sleep & retry, sensitive to tenant shutdown
    2880              :             // TODO: allow timeline deletion requests => should cancel the task
    2881              :         }
    2882              :     }
    2883              : 
    2884            0 :     async fn create_timeline_import_pgdata_task_impl(
    2885            0 :         self: Arc<Tenant>,
    2886            0 :         timeline: Arc<Timeline>,
    2887            0 :         index_part: import_pgdata::index_part_format::Root,
    2888            0 :         activate: ActivateTimelineArgs,
    2889            0 :         timeline_create_guard: TimelineCreateGuard,
    2890            0 :         ctx: RequestContext,
    2891            0 :     ) -> Result<(), anyhow::Error> {
    2892            0 :         info!("importing pgdata");
    2893            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2894            0 :             .await
    2895            0 :             .context("import")?;
    2896            0 :         info!("import done");
    2897              : 
    2898              :         //
    2899              :         // Reload timeline from remote.
    2900              :         // This proves that the remote state is attachable, and it reuses the code.
    2901              :         //
    2902              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2903              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2904              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2905              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2906              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2907              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2908              :         // to manifest because of the long runtime of this import task.
    2909              : 
    2910              :         //        in theory this shouldn't even .await anything except for coop yield
    2911            0 :         info!("shutting down timeline");
    2912            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2913            0 :         info!("timeline shut down, reloading from remote");
    2914              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2915              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2916              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2917              :         // };
    2918            0 :         let timeline_id = timeline.timeline_id;
    2919            0 : 
    2920            0 :         // load from object storage like Tenant::attach does
    2921            0 :         let resources = self.build_timeline_resources(timeline_id);
    2922            0 :         let index_part = resources
    2923            0 :             .remote_client
    2924            0 :             .download_index_file(&self.cancel)
    2925            0 :             .await?;
    2926            0 :         let index_part = match index_part {
    2927              :             MaybeDeletedIndexPart::Deleted(_) => {
    2928              :                 // likely concurrent delete call, cplane should prevent this
    2929            0 :                 anyhow::bail!(
    2930            0 :                     "index part says deleted but we are not done creating yet, this should not happen but"
    2931            0 :                 )
    2932              :             }
    2933            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2934            0 :         };
    2935            0 :         let metadata = index_part.metadata.clone();
    2936            0 :         self
    2937            0 :             .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
    2938            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2939            0 :             .await?
    2940            0 :             .ready_to_activate()
    2941            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2942              : 
    2943            0 :         anyhow::Ok(())
    2944            0 :     }
    2945              : 
    2946            0 :     pub(crate) async fn delete_timeline(
    2947            0 :         self: Arc<Self>,
    2948            0 :         timeline_id: TimelineId,
    2949            0 :     ) -> Result<(), DeleteTimelineError> {
    2950            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2951              : 
    2952            0 :         Ok(())
    2953            0 :     }
    2954              : 
    2955              :     /// perform one garbage collection iteration, removing old data files from disk.
    2956              :     /// this function is periodically called by gc task.
    2957              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2958              :     ///
    2959              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2960              :     ///
    2961              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2962              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2963              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2964              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2965              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2966              :     /// requires more history to be retained.
    2967              :     //
    2968         1508 :     pub(crate) async fn gc_iteration(
    2969         1508 :         &self,
    2970         1508 :         target_timeline_id: Option<TimelineId>,
    2971         1508 :         horizon: u64,
    2972         1508 :         pitr: Duration,
    2973         1508 :         cancel: &CancellationToken,
    2974         1508 :         ctx: &RequestContext,
    2975         1508 :     ) -> Result<GcResult, GcError> {
    2976         1508 :         // Don't start doing work during shutdown
    2977         1508 :         if let TenantState::Stopping { .. } = self.current_state() {
    2978            0 :             return Ok(GcResult::default());
    2979         1508 :         }
    2980         1508 : 
    2981         1508 :         // there is a global allowed_error for this
    2982         1508 :         if !self.is_active() {
    2983            0 :             return Err(GcError::NotActive);
    2984         1508 :         }
    2985         1508 : 
    2986         1508 :         {
    2987         1508 :             let conf = self.tenant_conf.load();
    2988         1508 : 
    2989         1508 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2990         1508 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2991         1508 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2992         1508 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2993         1508 :             if !conf.location.may_delete_layers_hint() {
    2994            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2995            0 :                 return Ok(GcResult::default());
    2996         1508 :             }
    2997         1508 : 
    2998         1508 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2999         1500 :                 info!("Skipping GC because lsn lease deadline is not reached");
    3000         1500 :                 return Ok(GcResult::default());
    3001            8 :             }
    3002              :         }
    3003              : 
    3004            8 :         let _guard = match self.gc_block.start().await {
    3005            8 :             Ok(guard) => guard,
    3006            0 :             Err(reasons) => {
    3007            0 :                 info!("Skipping GC: {reasons}");
    3008            0 :                 return Ok(GcResult::default());
    3009              :             }
    3010              :         };
    3011              : 
    3012            8 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3013            8 :             .await
    3014         1508 :     }
    3015              : 
    3016              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    3017              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    3018              :     /// immediate L0 compaction.
    3019              :     ///
    3020              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    3021            0 :     async fn compaction_iteration(
    3022            0 :         self: &Arc<Self>,
    3023            0 :         cancel: &CancellationToken,
    3024            0 :         ctx: &RequestContext,
    3025            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    3026            0 :         // Don't compact inactive tenants.
    3027            0 :         if !self.is_active() {
    3028            0 :             return Ok(CompactionOutcome::Skipped);
    3029            0 :         }
    3030            0 : 
    3031            0 :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    3032            0 :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    3033            0 :         let location = self.tenant_conf.load().location;
    3034            0 :         if !location.may_upload_layers_hint() {
    3035            0 :             info!("skipping compaction in location state {location:?}");
    3036            0 :             return Ok(CompactionOutcome::Skipped);
    3037            0 :         }
    3038            0 : 
    3039            0 :         // Don't compact if the circuit breaker is tripped.
    3040            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3041            0 :             info!("skipping compaction due to previous failures");
    3042            0 :             return Ok(CompactionOutcome::Skipped);
    3043            0 :         }
    3044            0 : 
    3045            0 :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3046            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3047            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3048            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3049            0 : 
    3050            0 :         {
    3051            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3052            0 :             let timelines = self.timelines.lock().unwrap();
    3053            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3054              :                 // Skip inactive timelines.
    3055            0 :                 if !timeline.is_active() {
    3056            0 :                     continue;
    3057            0 :                 }
    3058            0 : 
    3059            0 :                 // Schedule the timeline for compaction.
    3060            0 :                 compact.push(timeline.clone());
    3061              : 
    3062              :                 // Schedule the timeline for offloading if eligible.
    3063            0 :                 let can_offload = offload_enabled
    3064            0 :                     && timeline.can_offload().0
    3065            0 :                     && !timelines
    3066            0 :                         .iter()
    3067            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3068            0 :                 if can_offload {
    3069            0 :                     offload.insert(timeline_id);
    3070            0 :                 }
    3071              :             }
    3072              :         } // release timelines lock
    3073              : 
    3074            0 :         for timeline in &compact {
    3075              :             // Collect L0 counts. Can't await while holding lock above.
    3076            0 :             if let Ok(lm) = timeline.layers.read().await.layer_map() {
    3077            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3078            0 :             }
    3079              :         }
    3080              : 
    3081              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3082              :         // bound read amplification.
    3083              :         //
    3084              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3085              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3086              :         // splitting L0 and image/GC compaction to separate background jobs.
    3087            0 :         if self.get_compaction_l0_first() {
    3088            0 :             let compaction_threshold = self.get_compaction_threshold();
    3089            0 :             let compact_l0 = compact
    3090            0 :                 .iter()
    3091            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3092            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3093            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3094            0 :                 .rev()
    3095            0 :                 .map(|(tli, _)| tli.clone())
    3096            0 :                 .collect_vec();
    3097            0 : 
    3098            0 :             let mut has_pending_l0 = false;
    3099            0 :             for timeline in compact_l0 {
    3100            0 :                 let ctx = &ctx.with_scope_timeline(&timeline);
    3101              :                 // NB: don't set CompactFlags::YieldForL0, since this is an L0-only compaction pass.
    3102            0 :                 let outcome = timeline
    3103            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3104            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3105            0 :                     .await
    3106            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3107            0 :                 match outcome {
    3108            0 :                     CompactionOutcome::Done => {}
    3109            0 :                     CompactionOutcome::Skipped => {}
    3110            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3111            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3112              :                 }
    3113              :             }
    3114            0 :             if has_pending_l0 {
    3115            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3116            0 :             }
    3117            0 :         }
    3118              : 
    3119              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated more
    3120              :         // L0 layers, they may also be compacted here. Image compaction will yield if there is
    3121              :         // pending L0 compaction on any tenant timeline.
    3122              :         //
    3123              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3124              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3125            0 :         let mut has_pending = false;
    3126            0 :         for timeline in compact {
    3127            0 :             if !timeline.is_active() {
    3128            0 :                 continue;
    3129            0 :             }
    3130            0 :             let ctx = &ctx.with_scope_timeline(&timeline);
    3131            0 : 
    3132            0 :             // Yield for L0 if the separate L0 pass is enabled (otherwise there's no point).
    3133            0 :             let mut flags = EnumSet::default();
    3134            0 :             if self.get_compaction_l0_first() {
    3135            0 :                 flags |= CompactFlags::YieldForL0;
    3136            0 :             }
    3137              : 
    3138            0 :             let mut outcome = timeline
    3139            0 :                 .compact(cancel, flags, ctx)
    3140            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3141            0 :                 .await
    3142            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3143              : 
    3144              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3145            0 :             if outcome == CompactionOutcome::Done {
    3146            0 :                 let queue = {
    3147            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3148            0 :                     guard
    3149            0 :                         .entry(timeline.timeline_id)
    3150            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3151            0 :                         .clone()
    3152            0 :                 };
    3153            0 :                 outcome = queue
    3154            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3155            0 :                     .instrument(
    3156            0 :                         info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
    3157              :                     )
    3158            0 :                     .await?;
    3159            0 :             }
    3160              : 
    3161              :             // If we're done compacting, offload the timeline if requested.
    3162            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3163            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3164            0 :                 offload_timeline(self, &timeline)
    3165            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3166            0 :                     .await
    3167            0 :                     .or_else(|err| match err {
    3168              :                         // Ignore this, we likely raced with unarchival.
    3169            0 :                         OffloadError::NotArchived => Ok(()),
    3170            0 :                         err => Err(err),
    3171            0 :                     })?;
    3172            0 :             }
    3173              : 
    3174            0 :             match outcome {
    3175            0 :                 CompactionOutcome::Done => {}
    3176            0 :                 CompactionOutcome::Skipped => {}
    3177            0 :                 CompactionOutcome::Pending => has_pending = true,
    3178              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3179              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3180            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3181              :             }
    3182              :         }
    3183              : 
    3184              :         // Success! Untrip the breaker if necessary.
    3185            0 :         self.compaction_circuit_breaker
    3186            0 :             .lock()
    3187            0 :             .unwrap()
    3188            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3189            0 : 
    3190            0 :         match has_pending {
    3191            0 :             true => Ok(CompactionOutcome::Pending),
    3192            0 :             false => Ok(CompactionOutcome::Done),
    3193              :         }
    3194            0 :     }
    3195              : 
    3196              :     /// Trips the compaction circuit breaker if appropriate.
    3197            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3198            0 :         match err {
    3199            0 :             err if err.is_cancel() => {}
    3200            0 :             CompactionError::ShuttingDown => (),
    3201              :             // Offload failures don't trip the circuit breaker, since they're cheap to retry and
    3202              :             // shouldn't block compaction.
    3203            0 :             CompactionError::Offload(_) => {}
    3204            0 :             CompactionError::CollectKeySpaceError(err) => {
    3205            0 :                 // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
    3206            0 :                 self.compaction_circuit_breaker
    3207            0 :                     .lock()
    3208            0 :                     .unwrap()
    3209            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3210            0 :             }
    3211            0 :             CompactionError::Other(err) => {
    3212            0 :                 self.compaction_circuit_breaker
    3213            0 :                     .lock()
    3214            0 :                     .unwrap()
    3215            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3216            0 :             }
    3217            0 :             CompactionError::AlreadyRunning(_) => {}
    3218              :         }
    3219            0 :     }
    3220              : 
    3221              :     /// Cancel scheduled compaction tasks
    3222            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3223            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3224            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3225            0 :             q.cancel_scheduled();
    3226            0 :         }
    3227            0 :     }
    3228              : 
    3229            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3230            0 :         &self,
    3231            0 :         timeline_id: TimelineId,
    3232            0 :     ) -> Vec<CompactInfoResponse> {
    3233            0 :         let res = {
    3234            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3235            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3236              :         };
    3237            0 :         let Some((running, remaining)) = res else {
    3238            0 :             return Vec::new();
    3239              :         };
    3240            0 :         let mut result = Vec::new();
    3241            0 :         if let Some((id, running)) = running {
    3242            0 :             result.extend(running.into_compact_info_resp(id, true));
    3243            0 :         }
    3244            0 :         for (id, job) in remaining {
    3245            0 :             result.extend(job.into_compact_info_resp(id, false));
    3246            0 :         }
    3247            0 :         result
    3248            0 :     }
    3249              : 
    3250              :     /// Schedule a compaction task for a timeline.
    3251            0 :     pub(crate) async fn schedule_compaction(
    3252            0 :         &self,
    3253            0 :         timeline_id: TimelineId,
    3254            0 :         options: CompactOptions,
    3255            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3256            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3257            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3258            0 :         let q = guard
    3259            0 :             .entry(timeline_id)
    3260            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3261            0 :         q.schedule_manual_compaction(options, Some(tx));
    3262            0 :         Ok(rx)
    3263            0 :     }
    3264              : 
    3265              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3266            0 :     async fn housekeeping(&self) {
    3267            0 :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3268            0 :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3269            0 :         //
    3270            0 :         // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
    3271            0 :         // We don't run compaction in this case either, and don't want to keep flushing tiny L0
    3272            0 :         // layers that won't be compacted down.
    3273            0 :         if self.tenant_conf.load().location.may_upload_layers_hint() {
    3274            0 :             let timelines = self
    3275            0 :                 .timelines
    3276            0 :                 .lock()
    3277            0 :                 .unwrap()
    3278            0 :                 .values()
    3279            0 :                 .filter(|tli| tli.is_active())
    3280            0 :                 .cloned()
    3281            0 :                 .collect_vec();
    3282              : 
    3283            0 :             for timeline in timelines {
    3284            0 :                 timeline.maybe_freeze_ephemeral_layer().await;
    3285              :             }
    3286            0 :         }
    3287              : 
    3288              :         // Shut down walredo if idle.
    3289              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3290            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3291            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3292            0 :         }
    3293            0 :     }
    3294              : 
    3295            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3296            0 :         let timelines = self.timelines.lock().unwrap();
    3297            0 :         !timelines
    3298            0 :             .iter()
    3299            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3300            0 :     }
    3301              : 
    3302         3496 :     pub fn current_state(&self) -> TenantState {
    3303         3496 :         self.state.borrow().clone()
    3304         3496 :     }
    3305              : 
    3306         1972 :     pub fn is_active(&self) -> bool {
    3307         1972 :         self.current_state() == TenantState::Active
    3308         1972 :     }
    3309              : 
    3310            0 :     pub fn generation(&self) -> Generation {
    3311            0 :         self.generation
    3312            0 :     }
    3313              : 
    3314            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3315            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3316            0 :     }
    3317              : 
    3318              :     /// Changes tenant status to active, unless shutdown was already requested.
    3319              :     ///
    3320              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3321              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3322            0 :     fn activate(
    3323            0 :         self: &Arc<Self>,
    3324            0 :         broker_client: BrokerClientChannel,
    3325            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3326            0 :         ctx: &RequestContext,
    3327            0 :     ) {
    3328            0 :         span::debug_assert_current_span_has_tenant_id();
    3329            0 : 
    3330            0 :         let mut activating = false;
    3331            0 :         self.state.send_modify(|current_state| {
    3332              :             use pageserver_api::models::ActivatingFrom;
    3333            0 :             match &*current_state {
    3334              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3335            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3336              :                 }
    3337            0 :                 TenantState::Attaching => {
    3338            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3339            0 :                 }
    3340            0 :             }
    3341            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3342            0 :             activating = true;
    3343            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3344            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3345            0 :         });
    3346            0 : 
    3347            0 :         if activating {
    3348            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3349            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3350            0 :             let timelines_to_activate = timelines_accessor
    3351            0 :                 .values()
    3352            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3353            0 : 
    3354            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3355            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3356            0 : 
    3357            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3358            0 :             // down when they notice that the tenant is inactive.
    3359            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3360            0 : 
    3361            0 :             let mut activated_timelines = 0;
    3362              : 
    3363            0 :             for timeline in timelines_to_activate {
    3364            0 :                 timeline.activate(
    3365            0 :                     self.clone(),
    3366            0 :                     broker_client.clone(),
    3367            0 :                     background_jobs_can_start,
    3368            0 :                     &ctx.with_scope_timeline(timeline),
    3369            0 :                 );
    3370            0 :                 activated_timelines += 1;
    3371            0 :             }
    3372              : 
    3373            0 :             self.state.send_modify(move |current_state| {
    3374            0 :                 assert!(
    3375            0 :                     matches!(current_state, TenantState::Activating(_)),
    3376            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3377              :                 );
    3378            0 :                 *current_state = TenantState::Active;
    3379            0 : 
    3380            0 :                 let elapsed = self.constructed_at.elapsed();
    3381            0 :                 let total_timelines = timelines_accessor.len();
    3382            0 : 
    3383            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3384            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3385            0 :                 info!(
    3386            0 :                     since_creation_millis = elapsed.as_millis(),
    3387            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3388            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3389            0 :                     activated_timelines,
    3390            0 :                     total_timelines,
    3391            0 :                     post_state = <&'static str>::from(&*current_state),
    3392            0 :                     "activation attempt finished"
    3393              :                 );
    3394              : 
    3395            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3396            0 :             });
    3397            0 :         }
    3398            0 :     }
    3399              : 
    3400              :     /// Shutdown the tenant and join all of the spawned tasks.
    3401              :     ///
    3402              :     /// The method caters for all use-cases:
    3403              :     /// - pageserver shutdown (freeze_and_flush == true)
    3404              :     /// - detach + ignore (freeze_and_flush == false)
    3405              :     ///
    3406              :     /// This will attempt to shutdown even if tenant is broken.
    3407              :     ///
    3408              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3409              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3410              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3411              :     /// the ongoing shutdown.
    3412           12 :     async fn shutdown(
    3413           12 :         &self,
    3414           12 :         shutdown_progress: completion::Barrier,
    3415           12 :         shutdown_mode: timeline::ShutdownMode,
    3416           12 :     ) -> Result<(), completion::Barrier> {
    3417           12 :         span::debug_assert_current_span_has_tenant_id();
    3418              : 
    3419              :         // Set tenant (and its timlines) to Stoppping state.
    3420              :         //
    3421              :         // Since we can only transition into Stopping state after activation is complete,
    3422              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3423              :         //
    3424              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3425              :         // 1. Lock out any new requests to the tenants.
    3426              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3427              :         // 3. Signal cancellation for other tenant background loops.
    3428              :         // 4. ???
    3429              :         //
    3430              :         // The waiting for the cancellation is not done uniformly.
    3431              :         // We certainly wait for WAL receivers to shut down.
    3432              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3433              :         // But the tenant background loops are joined-on in our caller.
    3434              :         // It's mesed up.
    3435              :         // we just ignore the failure to stop
    3436              : 
    3437              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3438              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3439              :         // is very slow.
    3440           12 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3441            0 :             self.cancel.cancel();
    3442            0 : 
    3443            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3444            0 :             // are children of ours, so their flush loops will have shut down already
    3445            0 :             timeline::ShutdownMode::Hard
    3446              :         } else {
    3447           12 :             shutdown_mode
    3448              :         };
    3449              : 
    3450           12 :         match self.set_stopping(shutdown_progress).await {
    3451           12 :             Ok(()) => {}
    3452            0 :             Err(SetStoppingError::Broken) => {
    3453            0 :                 // assume that this is acceptable
    3454            0 :             }
    3455            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3456            0 :                 // give caller the option to wait for this this shutdown
    3457            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3458            0 :                 return Err(other);
    3459              :             }
    3460              :         };
    3461              : 
    3462           12 :         let mut js = tokio::task::JoinSet::new();
    3463           12 :         {
    3464           12 :             let timelines = self.timelines.lock().unwrap();
    3465           12 :             timelines.values().for_each(|timeline| {
    3466           12 :                 let timeline = Arc::clone(timeline);
    3467           12 :                 let timeline_id = timeline.timeline_id;
    3468           12 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3469           12 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3470           12 :             });
    3471           12 :         }
    3472           12 :         {
    3473           12 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3474           12 :             timelines_offloaded.values().for_each(|timeline| {
    3475            0 :                 timeline.defuse_for_tenant_drop();
    3476           12 :             });
    3477           12 :         }
    3478           12 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3479           12 :         tracing::info!("Waiting for timelines...");
    3480           24 :         while let Some(res) = js.join_next().await {
    3481            0 :             match res {
    3482           12 :                 Ok(()) => {}
    3483            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3484            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3485            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3486              :             }
    3487              :         }
    3488              : 
    3489           12 :         if let ShutdownMode::Reload = shutdown_mode {
    3490            0 :             tracing::info!("Flushing deletion queue");
    3491            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3492            0 :                 match e {
    3493            0 :                     DeletionQueueError::ShuttingDown => {
    3494            0 :                         // This is the only error we expect for now. In the future, if more error
    3495            0 :                         // variants are added, we should handle them here.
    3496            0 :                     }
    3497              :                 }
    3498            0 :             }
    3499           12 :         }
    3500              : 
    3501              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3502              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3503           12 :         tracing::debug!("Cancelling CancellationToken");
    3504           12 :         self.cancel.cancel();
    3505           12 : 
    3506           12 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3507           12 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3508           12 :         //
    3509           12 :         // this will additionally shutdown and await all timeline tasks.
    3510           12 :         tracing::debug!("Waiting for tasks...");
    3511           12 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3512              : 
    3513           12 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3514           12 :             walredo_mgr.shutdown().await;
    3515            0 :         }
    3516              : 
    3517              :         // Wait for any in-flight operations to complete
    3518           12 :         self.gate.close().await;
    3519              : 
    3520           12 :         remove_tenant_metrics(&self.tenant_shard_id);
    3521           12 : 
    3522           12 :         Ok(())
    3523           12 :     }
    3524              : 
    3525              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3526              :     ///
    3527              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3528              :     ///
    3529              :     /// This function is not cancel-safe!
    3530           12 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3531           12 :         let mut rx = self.state.subscribe();
    3532           12 : 
    3533           12 :         // cannot stop before we're done activating, so wait out until we're done activating
    3534           12 :         rx.wait_for(|state| match state {
    3535              :             TenantState::Activating(_) | TenantState::Attaching => {
    3536            0 :                 info!("waiting for {state} to turn Active|Broken|Stopping");
    3537            0 :                 false
    3538              :             }
    3539           12 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3540           12 :         })
    3541           12 :         .await
    3542           12 :         .expect("cannot drop self.state while on a &self method");
    3543           12 : 
    3544           12 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3545           12 :         let mut err = None;
    3546           12 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3547              :             TenantState::Activating(_) | TenantState::Attaching => {
    3548            0 :                 unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3549              :             }
    3550              :             TenantState::Active => {
    3551              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3552              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3553              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3554           12 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3555           12 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3556           12 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3557           12 :                 true
    3558              :             }
    3559              :             TenantState::Stopping { progress: None } => {
    3560              :                 // An attach was cancelled, and the attach transitioned the tenant from Attaching to
    3561              :                 // Stopping(None) to let us know it exited. Register our progress and continue.
    3562            0 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3563            0 :                 true
    3564              :             }
    3565            0 :             TenantState::Broken { reason, .. } => {
    3566            0 :                 info!(
    3567            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3568              :                 );
    3569            0 :                 err = Some(SetStoppingError::Broken);
    3570            0 :                 false
    3571              :             }
    3572            0 :             TenantState::Stopping { progress: Some(progress) } => {
    3573            0 :                 info!("Tenant is already in Stopping state");
    3574            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3575            0 :                 false
    3576              :             }
    3577           12 :         });
    3578           12 :         match (stopping, err) {
    3579           12 :             (true, None) => {} // continue
    3580            0 :             (false, Some(err)) => return Err(err),
    3581            0 :             (true, Some(_)) => unreachable!(
    3582            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3583            0 :             ),
    3584            0 :             (false, None) => unreachable!(
    3585            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3586            0 :             ),
    3587              :         }
    3588              : 
    3589           12 :         let timelines_accessor = self.timelines.lock().unwrap();
    3590           12 :         let not_broken_timelines = timelines_accessor
    3591           12 :             .values()
    3592           12 :             .filter(|timeline| !timeline.is_broken());
    3593           24 :         for timeline in not_broken_timelines {
    3594           12 :             timeline.set_state(TimelineState::Stopping);
    3595           12 :         }
    3596           12 :         Ok(())
    3597           12 :     }
    3598              : 
    3599              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3600              :     /// `remove_tenant_from_memory`
    3601              :     ///
    3602              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3603              :     ///
    3604              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3605            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3606            0 :         let mut rx = self.state.subscribe();
    3607            0 : 
    3608            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3609            0 :         // So, wait until it's done.
    3610            0 :         rx.wait_for(|state| match state {
    3611              :             TenantState::Activating(_) | TenantState::Attaching => {
    3612            0 :                 info!(
    3613            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3614            0 :                     <&'static str>::from(state)
    3615              :                 );
    3616            0 :                 false
    3617              :             }
    3618            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3619            0 :         })
    3620            0 :         .await
    3621            0 :         .expect("cannot drop self.state while on a &self method");
    3622            0 : 
    3623            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3624            0 :         self.set_broken_no_wait(reason)
    3625            0 :     }
    3626              : 
    3627            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3628            0 :         let reason = reason.to_string();
    3629            0 :         self.state.send_modify(|current_state| {
    3630            0 :             match *current_state {
    3631              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3632            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3633              :                 }
    3634              :                 TenantState::Active => {
    3635            0 :                     if cfg!(feature = "testing") {
    3636            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3637            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3638              :                     } else {
    3639            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3640              :                     }
    3641              :                 }
    3642              :                 TenantState::Broken { .. } => {
    3643            0 :                     warn!("Tenant is already in Broken state");
    3644              :                 }
    3645              :                 // This is the only "expected" path, any other path is a bug.
    3646              :                 TenantState::Stopping { .. } => {
    3647            0 :                     warn!(
    3648            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3649              :                         reason
    3650              :                     );
    3651            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3652              :                 }
    3653              :            }
    3654            0 :         });
    3655            0 :     }
    3656              : 
    3657            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3658            0 :         self.state.subscribe()
    3659            0 :     }
    3660              : 
    3661              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3662              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3663            0 :     pub(crate) fn activate_now(&self) {
    3664            0 :         self.activate_now_sem.add_permits(1);
    3665            0 :     }
    3666              : 
    3667            0 :     pub(crate) async fn wait_to_become_active(
    3668            0 :         &self,
    3669            0 :         timeout: Duration,
    3670            0 :     ) -> Result<(), GetActiveTenantError> {
    3671            0 :         let mut receiver = self.state.subscribe();
    3672              :         loop {
    3673            0 :             let current_state = receiver.borrow_and_update().clone();
    3674            0 :             match current_state {
    3675              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3676              :                     // in these states, there's a chance that we can reach ::Active
    3677            0 :                     self.activate_now();
    3678            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3679            0 :                         Ok(r) => {
    3680            0 :                             r.map_err(
    3681            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3682              :                                 // Tenant existed but was dropped: report it as non-existent
    3683            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3684            0 :                         )?
    3685              :                         }
    3686              :                         Err(TimeoutCancellableError::Cancelled) => {
    3687            0 :                             return Err(GetActiveTenantError::Cancelled);
    3688              :                         }
    3689              :                         Err(TimeoutCancellableError::Timeout) => {
    3690            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3691            0 :                                 latest_state: Some(self.current_state()),
    3692            0 :                                 wait_time: timeout,
    3693            0 :                             });
    3694              :                         }
    3695              :                     }
    3696              :                 }
    3697              :                 TenantState::Active => {
    3698            0 :                     return Ok(());
    3699              :                 }
    3700            0 :                 TenantState::Broken { reason, .. } => {
    3701            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3702            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3703            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3704              :                 }
    3705              :                 TenantState::Stopping { .. } => {
    3706              :                     // There's no chance the tenant can transition back into ::Active
    3707            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3708              :                 }
    3709              :             }
    3710              :         }
    3711            0 :     }
    3712              : 
    3713            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3714            0 :         self.tenant_conf.load().location.attach_mode
    3715            0 :     }
    3716              : 
    3717              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3718              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3719              :     /// rare external API calls, like a reconciliation at startup.
    3720            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3721            0 :         let attached_tenant_conf = self.tenant_conf.load();
    3722              : 
    3723            0 :         let location_config_mode = match attached_tenant_conf.location.attach_mode {
    3724            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3725            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3726            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3727              :         };
    3728              : 
    3729            0 :         models::LocationConfig {
    3730            0 :             mode: location_config_mode,
    3731            0 :             generation: self.generation.into(),
    3732            0 :             secondary_conf: None,
    3733            0 :             shard_number: self.shard_identity.number.0,
    3734            0 :             shard_count: self.shard_identity.count.literal(),
    3735            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3736            0 :             tenant_conf: attached_tenant_conf.tenant_conf.clone(),
    3737            0 :         }
    3738            0 :     }
    3739              : 
    3740            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3741            0 :         &self.tenant_shard_id
    3742            0 :     }
    3743              : 
    3744          468 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3745          468 :         self.shard_identity.stripe_size
    3746          468 :     }
    3747              : 
    3748            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3749            0 :         self.generation
    3750            0 :     }
    3751              : 
    3752              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3753              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3754              :     /// resetting this tenant to a valid state if we fail.
    3755            0 :     pub(crate) async fn split_prepare(
    3756            0 :         &self,
    3757            0 :         child_shards: &Vec<TenantShardId>,
    3758            0 :     ) -> anyhow::Result<()> {
    3759            0 :         let (timelines, offloaded) = {
    3760            0 :             let timelines = self.timelines.lock().unwrap();
    3761            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3762            0 :             (timelines.clone(), offloaded.clone())
    3763            0 :         };
    3764            0 :         let timelines_iter = timelines
    3765            0 :             .values()
    3766            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3767            0 :             .chain(
    3768            0 :                 offloaded
    3769            0 :                     .values()
    3770            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3771            0 :             );
    3772            0 :         for timeline in timelines_iter {
    3773              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3774              :             // to ensure that they do not start a split if currently in the process of doing these.
    3775              : 
    3776            0 :             let timeline_id = timeline.timeline_id();
    3777              : 
    3778            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3779              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3780              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3781              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3782            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3783            0 :                 timeline
    3784            0 :                     .remote_client
    3785            0 :                     .schedule_index_upload_for_file_changes()?;
    3786            0 :                 timeline.remote_client.wait_completion().await?;
    3787            0 :             }
    3788              : 
    3789            0 :             let remote_client = match timeline {
    3790            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3791            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3792            0 :                     let remote_client = self
    3793            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3794            0 :                     Arc::new(remote_client)
    3795              :                 }
    3796              :             };
    3797              : 
    3798              :             // Shut down the timeline's remote client: this means that the indices we write
    3799              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3800            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3801            0 :             remote_client.shutdown().await;
    3802              : 
    3803              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3804              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3805              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3806              :             // we use here really is the remotely persistent one).
    3807            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3808            0 :             let result = remote_client
    3809            0 :                 .download_index_file(&self.cancel)
    3810            0 :                 .instrument(info_span!("download_index_file", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))
    3811            0 :                 .await?;
    3812            0 :             let index_part = match result {
    3813              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3814            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3815              :                 }
    3816            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3817              :             };
    3818              : 
    3819            0 :             for child_shard in child_shards {
    3820            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3821            0 :                 upload_index_part(
    3822            0 :                     &self.remote_storage,
    3823            0 :                     child_shard,
    3824            0 :                     &timeline_id,
    3825            0 :                     self.generation,
    3826            0 :                     &index_part,
    3827            0 :                     &self.cancel,
    3828            0 :                 )
    3829            0 :                 .await?;
    3830              :             }
    3831              :         }
    3832              : 
    3833            0 :         let tenant_manifest = self.build_tenant_manifest();
    3834            0 :         for child_shard in child_shards {
    3835            0 :             tracing::info!(
    3836            0 :                 "Uploading tenant manifest for child {}",
    3837            0 :                 child_shard.to_index()
    3838              :             );
    3839            0 :             upload_tenant_manifest(
    3840            0 :                 &self.remote_storage,
    3841            0 :                 child_shard,
    3842            0 :                 self.generation,
    3843            0 :                 &tenant_manifest,
    3844            0 :                 &self.cancel,
    3845            0 :             )
    3846            0 :             .await?;
    3847              :         }
    3848              : 
    3849            0 :         Ok(())
    3850            0 :     }
    3851              : 
    3852            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3853            0 :         let mut result = TopTenantShardItem {
    3854            0 :             id: self.tenant_shard_id,
    3855            0 :             resident_size: 0,
    3856            0 :             physical_size: 0,
    3857            0 :             max_logical_size: 0,
    3858            0 :             max_logical_size_per_shard: 0,
    3859            0 :         };
    3860              : 
    3861            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3862            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3863            0 : 
    3864            0 :             result.physical_size += timeline
    3865            0 :                 .remote_client
    3866            0 :                 .metrics
    3867            0 :                 .remote_physical_size_gauge
    3868            0 :                 .get();
    3869            0 :             result.max_logical_size = std::cmp::max(
    3870            0 :                 result.max_logical_size,
    3871            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3872            0 :             );
    3873            0 :         }
    3874              : 
    3875            0 :         result.max_logical_size_per_shard = result
    3876            0 :             .max_logical_size
    3877            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    3878            0 : 
    3879            0 :         result
    3880            0 :     }
    3881              : }
    3882              : 
    3883              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3884              : /// perform a topological sort, so that the parent of each timeline comes
    3885              : /// before the children.
    3886              : /// E extracts the ancestor from T
    3887              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3888          464 : fn tree_sort_timelines<T, E>(
    3889          464 :     timelines: HashMap<TimelineId, T>,
    3890          464 :     extractor: E,
    3891          464 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3892          464 : where
    3893          464 :     E: Fn(&T) -> Option<TimelineId>,
    3894          464 : {
    3895          464 :     let mut result = Vec::with_capacity(timelines.len());
    3896          464 : 
    3897          464 :     let mut now = Vec::with_capacity(timelines.len());
    3898          464 :     // (ancestor, children)
    3899          464 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3900          464 :         HashMap::with_capacity(timelines.len());
    3901              : 
    3902          476 :     for (timeline_id, value) in timelines {
    3903           12 :         if let Some(ancestor_id) = extractor(&value) {
    3904            4 :             let children = later.entry(ancestor_id).or_default();
    3905            4 :             children.push((timeline_id, value));
    3906            8 :         } else {
    3907            8 :             now.push((timeline_id, value));
    3908            8 :         }
    3909              :     }
    3910              : 
    3911          476 :     while let Some((timeline_id, metadata)) = now.pop() {
    3912           12 :         result.push((timeline_id, metadata));
    3913              :         // All children of this can be loaded now
    3914           12 :         if let Some(mut children) = later.remove(&timeline_id) {
    3915            4 :             now.append(&mut children);
    3916            8 :         }
    3917              :     }
    3918              : 
    3919              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3920          464 :     if !later.is_empty() {
    3921            0 :         for (missing_id, orphan_ids) in later {
    3922            0 :             for (orphan_id, _) in orphan_ids {
    3923            0 :                 error!(
    3924            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    3925              :                 );
    3926              :             }
    3927              :         }
    3928            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3929          464 :     }
    3930          464 : 
    3931          464 :     Ok(result)
    3932          464 : }
    3933              : 
    3934              : enum ActivateTimelineArgs {
    3935              :     Yes {
    3936              :         broker_client: storage_broker::BrokerClientChannel,
    3937              :     },
    3938              :     No,
    3939              : }
    3940              : 
    3941              : impl Tenant {
    3942            0 :     pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
    3943            0 :         self.tenant_conf.load().tenant_conf.clone()
    3944            0 :     }
    3945              : 
    3946            0 :     pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
    3947            0 :         self.tenant_specific_overrides()
    3948            0 :             .merge(self.conf.default_tenant_conf.clone())
    3949            0 :     }
    3950              : 
    3951            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3952            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3953            0 :         tenant_conf
    3954            0 :             .checkpoint_distance
    3955            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3956            0 :     }
    3957              : 
    3958            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3959            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3960            0 :         tenant_conf
    3961            0 :             .checkpoint_timeout
    3962            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3963            0 :     }
    3964              : 
    3965            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3966            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3967            0 :         tenant_conf
    3968            0 :             .compaction_target_size
    3969            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3970            0 :     }
    3971              : 
    3972            0 :     pub fn get_compaction_period(&self) -> Duration {
    3973            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3974            0 :         tenant_conf
    3975            0 :             .compaction_period
    3976            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3977            0 :     }
    3978              : 
    3979            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3980            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3981            0 :         tenant_conf
    3982            0 :             .compaction_threshold
    3983            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3984            0 :     }
    3985              : 
    3986            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    3987            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3988            0 :         tenant_conf
    3989            0 :             .rel_size_v2_enabled
    3990            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    3991            0 :     }
    3992              : 
    3993            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    3994            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3995            0 :         tenant_conf
    3996            0 :             .compaction_upper_limit
    3997            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    3998            0 :     }
    3999              : 
    4000            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    4001            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4002            0 :         tenant_conf
    4003            0 :             .compaction_l0_first
    4004            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    4005            0 :     }
    4006              : 
    4007            8 :     pub fn get_gc_horizon(&self) -> u64 {
    4008            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4009            8 :         tenant_conf
    4010            8 :             .gc_horizon
    4011            8 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4012            8 :     }
    4013              : 
    4014            0 :     pub fn get_gc_period(&self) -> Duration {
    4015            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4016            0 :         tenant_conf
    4017            0 :             .gc_period
    4018            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4019            0 :     }
    4020              : 
    4021            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4022            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4023            0 :         tenant_conf
    4024            0 :             .image_creation_threshold
    4025            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4026            0 :     }
    4027              : 
    4028            8 :     pub fn get_pitr_interval(&self) -> Duration {
    4029            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4030            8 :         tenant_conf
    4031            8 :             .pitr_interval
    4032            8 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4033            8 :     }
    4034              : 
    4035            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4036            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4037            0 :         tenant_conf
    4038            0 :             .min_resident_size_override
    4039            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4040            0 :     }
    4041              : 
    4042            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4043            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4044            0 :         let heatmap_period = tenant_conf
    4045            0 :             .heatmap_period
    4046            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4047            0 :         if heatmap_period.is_zero() {
    4048            0 :             None
    4049              :         } else {
    4050            0 :             Some(heatmap_period)
    4051              :         }
    4052            0 :     }
    4053              : 
    4054            8 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4055            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4056            8 :         tenant_conf
    4057            8 :             .lsn_lease_length
    4058            8 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4059            8 :     }
    4060              : 
    4061            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4062            0 :         if self.conf.timeline_offloading {
    4063            0 :             return true;
    4064            0 :         }
    4065            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4066            0 :         tenant_conf
    4067            0 :             .timeline_offloading
    4068            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4069            0 :     }
    4070              : 
    4071              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4072          468 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4073          468 :         // Collect the offloaded timelines, and sort them for deterministic output.
    4074          468 :         let offloaded_timelines = self
    4075          468 :             .timelines_offloaded
    4076          468 :             .lock()
    4077          468 :             .unwrap()
    4078          468 :             .values()
    4079          468 :             .map(|tli| tli.manifest())
    4080          468 :             .sorted_by_key(|m| m.timeline_id)
    4081          468 :             .collect_vec();
    4082          468 : 
    4083          468 :         TenantManifest {
    4084          468 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4085          468 :             stripe_size: Some(self.get_shard_stripe_size()),
    4086          468 :             offloaded_timelines,
    4087          468 :         }
    4088          468 :     }
    4089              : 
    4090            0 :     pub fn update_tenant_config<
    4091            0 :         F: Fn(
    4092            0 :             pageserver_api::models::TenantConfig,
    4093            0 :         ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
    4094            0 :     >(
    4095            0 :         &self,
    4096            0 :         update: F,
    4097            0 :     ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
    4098            0 :         // Use read-copy-update in order to avoid overwriting the location config
    4099            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    4100            0 :         // this race is not possible if both request types come from the storage
    4101            0 :         // controller (as they should!) because an exclusive op lock is required
    4102            0 :         // on the storage controller side.
    4103            0 : 
    4104            0 :         self.tenant_conf
    4105            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4106            0 :                 Ok(Arc::new(AttachedTenantConf {
    4107            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4108            0 :                     location: attached_conf.location,
    4109            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4110              :                 }))
    4111            0 :             })?;
    4112              : 
    4113            0 :         let updated = self.tenant_conf.load();
    4114            0 : 
    4115            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    4116            0 :         // Don't hold self.timelines.lock() during the notifies.
    4117            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4118            0 :         // mutexes in struct Timeline in the future.
    4119            0 :         let timelines = self.list_timelines();
    4120            0 :         for timeline in timelines {
    4121            0 :             timeline.tenant_conf_updated(&updated);
    4122            0 :         }
    4123              : 
    4124            0 :         Ok(updated.tenant_conf.clone())
    4125            0 :     }
    4126              : 
    4127            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4128            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4129            0 : 
    4130            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4131            0 : 
    4132            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4133            0 :         // Don't hold self.timelines.lock() during the notifies.
    4134            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4135            0 :         // mutexes in struct Timeline in the future.
    4136            0 :         let timelines = self.list_timelines();
    4137            0 :         for timeline in timelines {
    4138            0 :             timeline.tenant_conf_updated(&new_conf);
    4139            0 :         }
    4140            0 :     }
    4141              : 
    4142          464 :     fn get_pagestream_throttle_config(
    4143          464 :         psconf: &'static PageServerConf,
    4144          464 :         overrides: &pageserver_api::models::TenantConfig,
    4145          464 :     ) -> throttle::Config {
    4146          464 :         overrides
    4147          464 :             .timeline_get_throttle
    4148          464 :             .clone()
    4149          464 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4150          464 :     }
    4151              : 
    4152            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
    4153            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4154            0 :         self.pagestream_throttle.reconfigure(conf)
    4155            0 :     }
    4156              : 
    4157              :     /// Helper function to create a new Timeline struct.
    4158              :     ///
    4159              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4160              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4161              :     /// map.
    4162              :     ///
    4163              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4164              :     /// and we might not have the ancestor present anymore which is fine for to be
    4165              :     /// deleted timelines.
    4166              :     #[allow(clippy::too_many_arguments)]
    4167          928 :     fn create_timeline_struct(
    4168          928 :         &self,
    4169          928 :         new_timeline_id: TimelineId,
    4170          928 :         new_metadata: &TimelineMetadata,
    4171          928 :         previous_heatmap: Option<PreviousHeatmap>,
    4172          928 :         ancestor: Option<Arc<Timeline>>,
    4173          928 :         resources: TimelineResources,
    4174          928 :         cause: CreateTimelineCause,
    4175          928 :         create_idempotency: CreateTimelineIdempotency,
    4176          928 :         gc_compaction_state: Option<GcCompactionState>,
    4177          928 :         rel_size_v2_status: Option<RelSizeMigration>,
    4178          928 :         ctx: &RequestContext,
    4179          928 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4180          928 :         let state = match cause {
    4181              :             CreateTimelineCause::Load => {
    4182          928 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4183          928 :                 anyhow::ensure!(
    4184          928 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4185            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4186              :                 );
    4187          928 :                 TimelineState::Loading
    4188              :             }
    4189            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4190              :         };
    4191              : 
    4192          928 :         let pg_version = new_metadata.pg_version();
    4193          928 : 
    4194          928 :         let timeline = Timeline::new(
    4195          928 :             self.conf,
    4196          928 :             Arc::clone(&self.tenant_conf),
    4197          928 :             new_metadata,
    4198          928 :             previous_heatmap,
    4199          928 :             ancestor,
    4200          928 :             new_timeline_id,
    4201          928 :             self.tenant_shard_id,
    4202          928 :             self.generation,
    4203          928 :             self.shard_identity,
    4204          928 :             self.walredo_mgr.clone(),
    4205          928 :             resources,
    4206          928 :             pg_version,
    4207          928 :             state,
    4208          928 :             self.attach_wal_lag_cooldown.clone(),
    4209          928 :             create_idempotency,
    4210          928 :             gc_compaction_state,
    4211          928 :             rel_size_v2_status,
    4212          928 :             self.cancel.child_token(),
    4213          928 :         );
    4214          928 : 
    4215          928 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4216          928 :             .scope(context::Scope::new_timeline(&timeline))
    4217          928 :             .detached_child();
    4218          928 : 
    4219          928 :         Ok((timeline, timeline_ctx))
    4220          928 :     }
    4221              : 
    4222              :     /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
    4223              :     /// to ensure proper cleanup of background tasks and metrics.
    4224              :     //
    4225              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4226              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4227              :     #[allow(clippy::too_many_arguments)]
    4228          464 :     fn new(
    4229          464 :         state: TenantState,
    4230          464 :         conf: &'static PageServerConf,
    4231          464 :         attached_conf: AttachedTenantConf,
    4232          464 :         shard_identity: ShardIdentity,
    4233          464 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4234          464 :         tenant_shard_id: TenantShardId,
    4235          464 :         remote_storage: GenericRemoteStorage,
    4236          464 :         deletion_queue_client: DeletionQueueClient,
    4237          464 :         l0_flush_global_state: L0FlushGlobalState,
    4238          464 :     ) -> Tenant {
    4239          464 :         debug_assert!(
    4240          464 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4241              :         );
    4242              : 
    4243          464 :         let (state, mut rx) = watch::channel(state);
    4244          464 : 
    4245          464 :         tokio::spawn(async move {
    4246          463 :             // reflect tenant state in metrics:
    4247          463 :             // - global per tenant state: TENANT_STATE_METRIC
    4248          463 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4249          463 :             //
    4250          463 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4251          463 :             // alerting.
    4252          463 : 
    4253          463 :             let tid = tenant_shard_id.to_string();
    4254          463 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4255          463 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4256              : 
    4257          926 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4258          926 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4259          926 :             }
    4260              : 
    4261          463 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4262          463 : 
    4263          463 :             let is_broken = tuple.1;
    4264          463 :             let mut counted_broken = if is_broken {
    4265              :                 // add the id to the set right away, there should not be any updates on the channel
    4266              :                 // after before tenant is removed, if ever
    4267            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4268            0 :                 true
    4269              :             } else {
    4270          463 :                 false
    4271              :             };
    4272              : 
    4273              :             loop {
    4274          926 :                 let labels = &tuple.0;
    4275          926 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4276          926 :                 current.inc();
    4277          926 : 
    4278          926 :                 if rx.changed().await.is_err() {
    4279              :                     // tenant has been dropped
    4280           28 :                     current.dec();
    4281           28 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4282           28 :                     break;
    4283          463 :                 }
    4284          463 : 
    4285          463 :                 current.dec();
    4286          463 :                 tuple = inspect_state(&rx.borrow_and_update());
    4287          463 : 
    4288          463 :                 let is_broken = tuple.1;
    4289          463 :                 if is_broken && !counted_broken {
    4290            0 :                     counted_broken = true;
    4291            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4292            0 :                     // access
    4293            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4294          463 :                 }
    4295              :             }
    4296          464 :         });
    4297          464 : 
    4298          464 :         Tenant {
    4299          464 :             tenant_shard_id,
    4300          464 :             shard_identity,
    4301          464 :             generation: attached_conf.location.generation,
    4302          464 :             conf,
    4303          464 :             // using now here is good enough approximation to catch tenants with really long
    4304          464 :             // activation times.
    4305          464 :             constructed_at: Instant::now(),
    4306          464 :             timelines: Mutex::new(HashMap::new()),
    4307          464 :             timelines_creating: Mutex::new(HashSet::new()),
    4308          464 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4309          464 :             remote_tenant_manifest: Default::default(),
    4310          464 :             gc_cs: tokio::sync::Mutex::new(()),
    4311          464 :             walredo_mgr,
    4312          464 :             remote_storage,
    4313          464 :             deletion_queue_client,
    4314          464 :             state,
    4315          464 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4316          464 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4317          464 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4318          464 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4319          464 :                 format!("compaction-{tenant_shard_id}"),
    4320          464 :                 5,
    4321          464 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4322          464 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4323          464 :                 // use an extremely long backoff.
    4324          464 :                 Some(Duration::from_secs(3600 * 24)),
    4325          464 :             )),
    4326          464 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4327          464 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4328          464 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4329          464 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4330          464 :             cancel: CancellationToken::default(),
    4331          464 :             gate: Gate::default(),
    4332          464 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4333          464 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4334          464 :             )),
    4335          464 :             pagestream_throttle_metrics: Arc::new(
    4336          464 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4337          464 :             ),
    4338          464 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4339          464 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4340          464 :             gc_block: Default::default(),
    4341          464 :             l0_flush_global_state,
    4342          464 :         }
    4343          464 :     }
    4344              : 
    4345              :     /// Locate and load config
    4346            0 :     pub(super) fn load_tenant_config(
    4347            0 :         conf: &'static PageServerConf,
    4348            0 :         tenant_shard_id: &TenantShardId,
    4349            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4350            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4351            0 : 
    4352            0 :         info!("loading tenant configuration from {config_path}");
    4353              : 
    4354              :         // load and parse file
    4355            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4356            0 :             match e.kind() {
    4357              :                 std::io::ErrorKind::NotFound => {
    4358              :                     // The config should almost always exist for a tenant directory:
    4359              :                     //  - When attaching a tenant, the config is the first thing we write
    4360              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4361              :                     //    before deleting contents.
    4362              :                     //
    4363              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4364              :                     // between creating directory and writing config.  Callers should handle that as if the
    4365              :                     // directory didn't exist.
    4366              : 
    4367            0 :                     LoadConfigError::NotFound(config_path)
    4368              :                 }
    4369              :                 _ => {
    4370              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4371              :                     // that we cannot cleanly recover
    4372            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4373              :                 }
    4374              :             }
    4375            0 :         })?;
    4376              : 
    4377            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4378            0 :     }
    4379              : 
    4380              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4381              :     pub(super) async fn persist_tenant_config(
    4382              :         conf: &'static PageServerConf,
    4383              :         tenant_shard_id: &TenantShardId,
    4384              :         location_conf: &LocationConf,
    4385              :     ) -> std::io::Result<()> {
    4386              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4387              : 
    4388              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4389              :     }
    4390              : 
    4391              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4392              :     pub(super) async fn persist_tenant_config_at(
    4393              :         tenant_shard_id: &TenantShardId,
    4394              :         config_path: &Utf8Path,
    4395              :         location_conf: &LocationConf,
    4396              :     ) -> std::io::Result<()> {
    4397              :         debug!("persisting tenantconf to {config_path}");
    4398              : 
    4399              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4400              : #  It is read in case of pageserver restart.
    4401              : "#
    4402              :         .to_string();
    4403              : 
    4404            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4405            0 :             Err(std::io::Error::other("tenant-config-before-write"))
    4406            0 :         });
    4407              : 
    4408              :         // Convert the config to a toml file.
    4409              :         conf_content +=
    4410              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4411              : 
    4412              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4413              : 
    4414              :         let conf_content = conf_content.into_bytes();
    4415              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4416              :     }
    4417              : 
    4418              :     //
    4419              :     // How garbage collection works:
    4420              :     //
    4421              :     //                    +--bar------------->
    4422              :     //                   /
    4423              :     //             +----+-----foo---------------->
    4424              :     //            /
    4425              :     // ----main--+-------------------------->
    4426              :     //                \
    4427              :     //                 +-----baz-------->
    4428              :     //
    4429              :     //
    4430              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4431              :     //    `gc_infos` are being refreshed
    4432              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4433              :     //    all the points where other timelines have been branched off.
    4434              :     //    We will refrain from removing page versions at those LSNs.
    4435              :     // 3. For each timeline, scan all layer files on the timeline.
    4436              :     //    Remove all files for which a newer file exists and which
    4437              :     //    don't cover any branch point LSNs.
    4438              :     //
    4439              :     // TODO:
    4440              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4441              :     //   don't need to keep that in the parent anymore. But currently
    4442              :     //   we do.
    4443            8 :     async fn gc_iteration_internal(
    4444            8 :         &self,
    4445            8 :         target_timeline_id: Option<TimelineId>,
    4446            8 :         horizon: u64,
    4447            8 :         pitr: Duration,
    4448            8 :         cancel: &CancellationToken,
    4449            8 :         ctx: &RequestContext,
    4450            8 :     ) -> Result<GcResult, GcError> {
    4451            8 :         let mut totals: GcResult = Default::default();
    4452            8 :         let now = Instant::now();
    4453              : 
    4454            8 :         let gc_timelines = self
    4455            8 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4456            8 :             .await?;
    4457              : 
    4458            8 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4459              : 
    4460              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4461            8 :         if !gc_timelines.is_empty() {
    4462            8 :             info!("{} timelines need GC", gc_timelines.len());
    4463              :         } else {
    4464            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4465              :         }
    4466              : 
    4467              :         // Perform GC for each timeline.
    4468              :         //
    4469              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4470              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4471              :         // with branch creation.
    4472              :         //
    4473              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4474              :         // creation task can run concurrently with timeline's GC iteration.
    4475           16 :         for timeline in gc_timelines {
    4476            8 :             if cancel.is_cancelled() {
    4477              :                 // We were requested to shut down. Stop and return with the progress we
    4478              :                 // made.
    4479            0 :                 break;
    4480            8 :             }
    4481            8 :             let result = match timeline.gc().await {
    4482              :                 Err(GcError::TimelineCancelled) => {
    4483            0 :                     if target_timeline_id.is_some() {
    4484              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4485            0 :                         return Err(GcError::TimelineCancelled);
    4486              :                     } else {
    4487              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4488              :                         // skip past this and proceed to try GC on other timelines.
    4489            0 :                         continue;
    4490              :                     }
    4491              :                 }
    4492            8 :                 r => r?,
    4493              :             };
    4494            8 :             totals += result;
    4495              :         }
    4496              : 
    4497            8 :         totals.elapsed = now.elapsed();
    4498            8 :         Ok(totals)
    4499            8 :     }
    4500              : 
    4501              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4502              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4503              :     /// [`Tenant::get_gc_horizon`].
    4504              :     ///
    4505              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4506            8 :     pub(crate) async fn refresh_gc_info(
    4507            8 :         &self,
    4508            8 :         cancel: &CancellationToken,
    4509            8 :         ctx: &RequestContext,
    4510            8 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4511            8 :         // since this method can now be called at different rates than the configured gc loop, it
    4512            8 :         // might be that these configuration values get applied faster than what it was previously,
    4513            8 :         // since these were only read from the gc task.
    4514            8 :         let horizon = self.get_gc_horizon();
    4515            8 :         let pitr = self.get_pitr_interval();
    4516            8 : 
    4517            8 :         // refresh all timelines
    4518            8 :         let target_timeline_id = None;
    4519            8 : 
    4520            8 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4521            8 :             .await
    4522            8 :     }
    4523              : 
    4524              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4525              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4526              :     ///
    4527              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4528            0 :     fn initialize_gc_info(
    4529            0 :         &self,
    4530            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4531            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4532            0 :         restrict_to_timeline: Option<TimelineId>,
    4533            0 :     ) {
    4534            0 :         if restrict_to_timeline.is_none() {
    4535              :             // This function must be called before activation: after activation timeline create/delete operations
    4536              :             // might happen, and this function is not safe to run concurrently with those.
    4537            0 :             assert!(!self.is_active());
    4538            0 :         }
    4539              : 
    4540              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4541              :         // the branch point where it was created.
    4542            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4543            0 :             BTreeMap::new();
    4544            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4545            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4546            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4547            0 :                 ancestor_children.push((
    4548            0 :                     timeline_entry.get_ancestor_lsn(),
    4549            0 :                     *timeline_id,
    4550            0 :                     MaybeOffloaded::No,
    4551            0 :                 ));
    4552            0 :             }
    4553            0 :         });
    4554            0 :         timelines_offloaded
    4555            0 :             .iter()
    4556            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4557            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4558            0 :                     return;
    4559              :                 };
    4560            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4561            0 :                     return;
    4562              :                 };
    4563            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4564            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4565            0 :             });
    4566            0 : 
    4567            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4568            0 :         let horizon = self.get_gc_horizon();
    4569              : 
    4570              :         // Populate each timeline's GcInfo with information about its child branches
    4571            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4572            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4573              :         } else {
    4574            0 :             itertools::Either::Right(timelines.values())
    4575              :         };
    4576            0 :         for timeline in timelines_to_write {
    4577            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4578            0 :                 .remove(&timeline.timeline_id)
    4579            0 :                 .unwrap_or_default();
    4580            0 : 
    4581            0 :             branchpoints.sort_by_key(|b| b.0);
    4582            0 : 
    4583            0 :             let mut target = timeline.gc_info.write().unwrap();
    4584            0 : 
    4585            0 :             target.retain_lsns = branchpoints;
    4586            0 : 
    4587            0 :             let space_cutoff = timeline
    4588            0 :                 .get_last_record_lsn()
    4589            0 :                 .checked_sub(horizon)
    4590            0 :                 .unwrap_or(Lsn(0));
    4591            0 : 
    4592            0 :             target.cutoffs = GcCutoffs {
    4593            0 :                 space: space_cutoff,
    4594            0 :                 time: Lsn::INVALID,
    4595            0 :             };
    4596            0 :         }
    4597            0 :     }
    4598              : 
    4599           16 :     async fn refresh_gc_info_internal(
    4600           16 :         &self,
    4601           16 :         target_timeline_id: Option<TimelineId>,
    4602           16 :         horizon: u64,
    4603           16 :         pitr: Duration,
    4604           16 :         cancel: &CancellationToken,
    4605           16 :         ctx: &RequestContext,
    4606           16 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4607           16 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4608           16 :         // currently visible timelines.
    4609           16 :         let timelines = self
    4610           16 :             .timelines
    4611           16 :             .lock()
    4612           16 :             .unwrap()
    4613           16 :             .values()
    4614           40 :             .filter(|tl| match target_timeline_id.as_ref() {
    4615            8 :                 Some(target) => &tl.timeline_id == target,
    4616           32 :                 None => true,
    4617           40 :             })
    4618           16 :             .cloned()
    4619           16 :             .collect::<Vec<_>>();
    4620           16 : 
    4621           16 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4622              :             // We were to act on a particular timeline and it wasn't found
    4623            0 :             return Err(GcError::TimelineNotFound);
    4624           16 :         }
    4625           16 : 
    4626           16 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4627           16 :             HashMap::with_capacity(timelines.len());
    4628           16 : 
    4629           16 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4630           16 :         let now_ts_for_pitr_calc = SystemTime::now();
    4631           40 :         for timeline in timelines.iter() {
    4632           40 :             let ctx = &ctx.with_scope_timeline(timeline);
    4633           40 :             let cutoff = timeline
    4634           40 :                 .get_last_record_lsn()
    4635           40 :                 .checked_sub(horizon)
    4636           40 :                 .unwrap_or(Lsn(0));
    4637              : 
    4638           40 :             let cutoffs = timeline
    4639           40 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4640           40 :                 .await?;
    4641           40 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4642           40 :             assert!(old.is_none());
    4643              :         }
    4644              : 
    4645           16 :         if !self.is_active() || self.cancel.is_cancelled() {
    4646            0 :             return Err(GcError::TenantCancelled);
    4647           16 :         }
    4648              : 
    4649              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4650              :         // because that will stall branch creation.
    4651           16 :         let gc_cs = self.gc_cs.lock().await;
    4652              : 
    4653              :         // Ok, we now know all the branch points.
    4654              :         // Update the GC information for each timeline.
    4655           16 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4656           56 :         for timeline in timelines {
    4657              :             // We filtered the timeline list above
    4658           40 :             if let Some(target_timeline_id) = target_timeline_id {
    4659            8 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4660           32 :             }
    4661              : 
    4662              :             {
    4663           40 :                 let mut target = timeline.gc_info.write().unwrap();
    4664           40 : 
    4665           40 :                 // Cull any expired leases
    4666           40 :                 let now = SystemTime::now();
    4667           40 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4668           40 : 
    4669           40 :                 timeline
    4670           40 :                     .metrics
    4671           40 :                     .valid_lsn_lease_count_gauge
    4672           40 :                     .set(target.leases.len() as u64);
    4673              : 
    4674              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4675           40 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4676           24 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4677           24 :                         target.within_ancestor_pitr =
    4678           24 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4679           24 :                     }
    4680           16 :                 }
    4681              : 
    4682              :                 // Update metrics that depend on GC state
    4683           40 :                 timeline
    4684           40 :                     .metrics
    4685           40 :                     .archival_size
    4686           40 :                     .set(if target.within_ancestor_pitr {
    4687            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4688              :                     } else {
    4689           40 :                         0
    4690              :                     });
    4691           40 :                 timeline.metrics.pitr_history_size.set(
    4692           40 :                     timeline
    4693           40 :                         .get_last_record_lsn()
    4694           40 :                         .checked_sub(target.cutoffs.time)
    4695           40 :                         .unwrap_or(Lsn(0))
    4696           40 :                         .0,
    4697           40 :                 );
    4698              : 
    4699              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4700              :                 // - this timeline was created while we were finding cutoffs
    4701              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4702           40 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4703           40 :                     let original_cutoffs = target.cutoffs.clone();
    4704           40 :                     // GC cutoffs should never go back
    4705           40 :                     target.cutoffs = GcCutoffs {
    4706           40 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4707           40 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4708           40 :                     }
    4709            0 :                 }
    4710              :             }
    4711              : 
    4712           40 :             gc_timelines.push(timeline);
    4713              :         }
    4714           16 :         drop(gc_cs);
    4715           16 :         Ok(gc_timelines)
    4716           16 :     }
    4717              : 
    4718              :     /// A substitute for `branch_timeline` for use in unit tests.
    4719              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4720              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4721              :     /// timeline background tasks are launched, except the flush loop.
    4722              :     #[cfg(test)]
    4723          476 :     async fn branch_timeline_test(
    4724          476 :         self: &Arc<Self>,
    4725          476 :         src_timeline: &Arc<Timeline>,
    4726          476 :         dst_id: TimelineId,
    4727          476 :         ancestor_lsn: Option<Lsn>,
    4728          476 :         ctx: &RequestContext,
    4729          476 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4730          476 :         let tl = self
    4731          476 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4732          476 :             .await?
    4733          468 :             .into_timeline_for_test();
    4734          468 :         tl.set_state(TimelineState::Active);
    4735          468 :         Ok(tl)
    4736          476 :     }
    4737              : 
    4738              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4739              :     #[cfg(test)]
    4740              :     #[allow(clippy::too_many_arguments)]
    4741           24 :     pub async fn branch_timeline_test_with_layers(
    4742           24 :         self: &Arc<Self>,
    4743           24 :         src_timeline: &Arc<Timeline>,
    4744           24 :         dst_id: TimelineId,
    4745           24 :         ancestor_lsn: Option<Lsn>,
    4746           24 :         ctx: &RequestContext,
    4747           24 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4748           24 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4749           24 :         end_lsn: Lsn,
    4750           24 :     ) -> anyhow::Result<Arc<Timeline>> {
    4751              :         use checks::check_valid_layermap;
    4752              :         use itertools::Itertools;
    4753              : 
    4754           24 :         let tline = self
    4755           24 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4756           24 :             .await?;
    4757           24 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4758           24 :             ancestor_lsn
    4759              :         } else {
    4760            0 :             tline.get_last_record_lsn()
    4761              :         };
    4762           24 :         assert!(end_lsn >= ancestor_lsn);
    4763           24 :         tline.force_advance_lsn(end_lsn);
    4764           36 :         for deltas in delta_layer_desc {
    4765           12 :             tline
    4766           12 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4767           12 :                 .await?;
    4768              :         }
    4769           32 :         for (lsn, images) in image_layer_desc {
    4770            8 :             tline
    4771            8 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4772            8 :                 .await?;
    4773              :         }
    4774           24 :         let layer_names = tline
    4775           24 :             .layers
    4776           24 :             .read()
    4777           24 :             .await
    4778           24 :             .layer_map()
    4779           24 :             .unwrap()
    4780           24 :             .iter_historic_layers()
    4781           24 :             .map(|layer| layer.layer_name())
    4782           24 :             .collect_vec();
    4783           24 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4784            0 :             bail!("invalid layermap: {err}");
    4785           24 :         }
    4786           24 :         Ok(tline)
    4787           24 :     }
    4788              : 
    4789              :     /// Branch an existing timeline.
    4790            0 :     async fn branch_timeline(
    4791            0 :         self: &Arc<Self>,
    4792            0 :         src_timeline: &Arc<Timeline>,
    4793            0 :         dst_id: TimelineId,
    4794            0 :         start_lsn: Option<Lsn>,
    4795            0 :         ctx: &RequestContext,
    4796            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4797            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4798            0 :             .await
    4799            0 :     }
    4800              : 
    4801          476 :     async fn branch_timeline_impl(
    4802          476 :         self: &Arc<Self>,
    4803          476 :         src_timeline: &Arc<Timeline>,
    4804          476 :         dst_id: TimelineId,
    4805          476 :         start_lsn: Option<Lsn>,
    4806          476 :         ctx: &RequestContext,
    4807          476 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4808          476 :         let src_id = src_timeline.timeline_id;
    4809              : 
    4810              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4811              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4812              :         // valid while we are creating the branch.
    4813          476 :         let _gc_cs = self.gc_cs.lock().await;
    4814              : 
    4815              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4816          476 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4817            4 :             let lsn = src_timeline.get_last_record_lsn();
    4818            4 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4819            4 :             lsn
    4820          476 :         });
    4821              : 
    4822              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4823          476 :         let timeline_create_guard = match self
    4824          476 :             .start_creating_timeline(
    4825          476 :                 dst_id,
    4826          476 :                 CreateTimelineIdempotency::Branch {
    4827          476 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4828          476 :                     ancestor_start_lsn: start_lsn,
    4829          476 :                 },
    4830          476 :             )
    4831          476 :             .await?
    4832              :         {
    4833          476 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4834            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4835            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4836              :             }
    4837              :         };
    4838              : 
    4839              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4840              :         // horizon on the source timeline
    4841              :         //
    4842              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4843              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4844              :         // planned GC cutoff in 'gc_info' is normally larger than
    4845              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    4846              :         // changed the GC settings for the tenant to make the PITR window
    4847              :         // larger, but some of the data was already removed by an earlier GC
    4848              :         // iteration.
    4849              : 
    4850              :         // check against last actual 'latest_gc_cutoff' first
    4851          476 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    4852          476 :         {
    4853          476 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4854          476 :             let planned_cutoff = gc_info.min_cutoff();
    4855          476 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    4856            0 :                 tracing::info!(
    4857            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    4858            0 :                     *applied_gc_cutoff_lsn
    4859              :                 );
    4860              :             } else {
    4861          476 :                 src_timeline
    4862          476 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    4863          476 :                     .context(format!(
    4864          476 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    4865          476 :                         *applied_gc_cutoff_lsn,
    4866          476 :                     ))
    4867          476 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    4868              : 
    4869              :                 // and then the planned GC cutoff
    4870          468 :                 if start_lsn < planned_cutoff {
    4871            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4872            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    4873            0 :                     )));
    4874          468 :                 }
    4875              :             }
    4876              :         }
    4877              : 
    4878              :         //
    4879              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4880              :         // so that GC cannot advance the GC cutoff until we are finished.
    4881              :         // Proceed with the branch creation.
    4882              :         //
    4883              : 
    4884              :         // Determine prev-LSN for the new timeline. We can only determine it if
    4885              :         // the timeline was branched at the current end of the source timeline.
    4886              :         let RecordLsn {
    4887          468 :             last: src_last,
    4888          468 :             prev: src_prev,
    4889          468 :         } = src_timeline.get_last_record_rlsn();
    4890          468 :         let dst_prev = if src_last == start_lsn {
    4891          432 :             Some(src_prev)
    4892              :         } else {
    4893           36 :             None
    4894              :         };
    4895              : 
    4896              :         // Create the metadata file, noting the ancestor of the new timeline.
    4897              :         // There is initially no data in it, but all the read-calls know to look
    4898              :         // into the ancestor.
    4899          468 :         let metadata = TimelineMetadata::new(
    4900          468 :             start_lsn,
    4901          468 :             dst_prev,
    4902          468 :             Some(src_id),
    4903          468 :             start_lsn,
    4904          468 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4905          468 :             src_timeline.initdb_lsn,
    4906          468 :             src_timeline.pg_version,
    4907          468 :         );
    4908              : 
    4909          468 :         let (uninitialized_timeline, _timeline_ctx) = self
    4910          468 :             .prepare_new_timeline(
    4911          468 :                 dst_id,
    4912          468 :                 &metadata,
    4913          468 :                 timeline_create_guard,
    4914          468 :                 start_lsn + 1,
    4915          468 :                 Some(Arc::clone(src_timeline)),
    4916          468 :                 Some(src_timeline.get_rel_size_v2_status()),
    4917          468 :                 ctx,
    4918          468 :             )
    4919          468 :             .await?;
    4920              : 
    4921          468 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    4922              : 
    4923              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4924              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4925              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4926              :         // could get incorrect information and remove more layers, than needed.
    4927              :         // See also https://github.com/neondatabase/neon/issues/3865
    4928          468 :         new_timeline
    4929          468 :             .remote_client
    4930          468 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4931          468 :             .context("branch initial metadata upload")?;
    4932              : 
    4933              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4934              : 
    4935          468 :         Ok(CreateTimelineResult::Created(new_timeline))
    4936          476 :     }
    4937              : 
    4938              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4939              :     #[cfg(test)]
    4940              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4941              :     pub(crate) async fn bootstrap_timeline_test(
    4942              :         self: &Arc<Self>,
    4943              :         timeline_id: TimelineId,
    4944              :         pg_version: u32,
    4945              :         load_existing_initdb: Option<TimelineId>,
    4946              :         ctx: &RequestContext,
    4947              :     ) -> anyhow::Result<Arc<Timeline>> {
    4948              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4949              :             .await
    4950              :             .map_err(anyhow::Error::new)
    4951            4 :             .map(|r| r.into_timeline_for_test())
    4952              :     }
    4953              : 
    4954              :     /// Get exclusive access to the timeline ID for creation.
    4955              :     ///
    4956              :     /// Timeline-creating code paths must use this function before making changes
    4957              :     /// to in-memory or persistent state.
    4958              :     ///
    4959              :     /// The `state` parameter is a description of the timeline creation operation
    4960              :     /// we intend to perform.
    4961              :     /// If the timeline was already created in the meantime, we check whether this
    4962              :     /// request conflicts or is idempotent , based on `state`.
    4963          928 :     async fn start_creating_timeline(
    4964          928 :         self: &Arc<Self>,
    4965          928 :         new_timeline_id: TimelineId,
    4966          928 :         idempotency: CreateTimelineIdempotency,
    4967          928 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4968          928 :         let allow_offloaded = false;
    4969          928 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4970          924 :             Ok(create_guard) => {
    4971          924 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4972          924 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4973              :             }
    4974            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4975              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4976              :                 // Creation is in progress, we cannot create it again, and we cannot
    4977              :                 // check if this request matches the existing one, so caller must try
    4978              :                 // again later.
    4979            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4980              :             }
    4981            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4982              :             Err(TimelineExclusionError::AlreadyExists {
    4983            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4984            0 :                 ..
    4985            0 :             }) => {
    4986            0 :                 info!("timeline already exists but is offloaded");
    4987            0 :                 Err(CreateTimelineError::Conflict)
    4988              :             }
    4989              :             Err(TimelineExclusionError::AlreadyExists {
    4990            4 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4991            4 :                 arg,
    4992            4 :             }) => {
    4993            4 :                 {
    4994            4 :                     let existing = &existing.create_idempotency;
    4995            4 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4996            4 :                     debug!("timeline already exists");
    4997              : 
    4998            4 :                     match (existing, &arg) {
    4999              :                         // FailWithConflict => no idempotency check
    5000              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5001              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5002            4 :                             warn!("timeline already exists, failing request");
    5003            4 :                             return Err(CreateTimelineError::Conflict);
    5004              :                         }
    5005              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    5006            0 :                         (x, y) if x == y => {
    5007            0 :                             info!(
    5008            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    5009              :                             );
    5010              :                             // fallthrough
    5011              :                         }
    5012              :                         (_, _) => {
    5013            0 :                             warn!("idempotency conflict, failing request");
    5014            0 :                             return Err(CreateTimelineError::Conflict);
    5015              :                         }
    5016              :                     }
    5017              :                 }
    5018              : 
    5019            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5020              :             }
    5021              :         }
    5022          928 :     }
    5023              : 
    5024            0 :     async fn upload_initdb(
    5025            0 :         &self,
    5026            0 :         timelines_path: &Utf8PathBuf,
    5027            0 :         pgdata_path: &Utf8PathBuf,
    5028            0 :         timeline_id: &TimelineId,
    5029            0 :     ) -> anyhow::Result<()> {
    5030            0 :         let temp_path = timelines_path.join(format!(
    5031            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5032            0 :         ));
    5033            0 : 
    5034            0 :         scopeguard::defer! {
    5035            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    5036            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5037            0 :             }
    5038            0 :         }
    5039              : 
    5040            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5041              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5042            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5043            0 :             warn!(
    5044            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5045              :             );
    5046            0 :         }
    5047              : 
    5048            0 :         pausable_failpoint!("before-initdb-upload");
    5049              : 
    5050            0 :         backoff::retry(
    5051            0 :             || async {
    5052            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5053            0 :                     &self.remote_storage,
    5054            0 :                     &self.tenant_shard_id.tenant_id,
    5055            0 :                     timeline_id,
    5056            0 :                     pgdata_zstd.try_clone().await?,
    5057            0 :                     tar_zst_size,
    5058            0 :                     &self.cancel,
    5059            0 :                 )
    5060            0 :                 .await
    5061            0 :             },
    5062            0 :             |_| false,
    5063            0 :             3,
    5064            0 :             u32::MAX,
    5065            0 :             "persist_initdb_tar_zst",
    5066            0 :             &self.cancel,
    5067            0 :         )
    5068            0 :         .await
    5069            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5070            0 :         .and_then(|x| x)
    5071            0 :     }
    5072              : 
    5073              :     /// - run initdb to init temporary instance and get bootstrap data
    5074              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5075            4 :     async fn bootstrap_timeline(
    5076            4 :         self: &Arc<Self>,
    5077            4 :         timeline_id: TimelineId,
    5078            4 :         pg_version: u32,
    5079            4 :         load_existing_initdb: Option<TimelineId>,
    5080            4 :         ctx: &RequestContext,
    5081            4 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5082            4 :         let timeline_create_guard = match self
    5083            4 :             .start_creating_timeline(
    5084            4 :                 timeline_id,
    5085            4 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5086            4 :             )
    5087            4 :             .await?
    5088              :         {
    5089            4 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5090            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5091            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5092              :             }
    5093              :         };
    5094              : 
    5095              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5096              :         // temporary directory for basebackup files for the given timeline.
    5097              : 
    5098            4 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5099            4 :         let pgdata_path = path_with_suffix_extension(
    5100            4 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5101            4 :             TEMP_FILE_SUFFIX,
    5102            4 :         );
    5103            4 : 
    5104            4 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5105            4 :         // we won't race with other creations or existent timelines with the same path.
    5106            4 :         if pgdata_path.exists() {
    5107            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5108            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5109            0 :             })?;
    5110            0 :             tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
    5111            4 :         }
    5112              : 
    5113              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5114            4 :         let pgdata_path_deferred = pgdata_path.clone();
    5115            4 :         scopeguard::defer! {
    5116            4 :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5117            4 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5118            4 :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5119            4 :             } else {
    5120            4 :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5121            4 :             }
    5122            4 :         }
    5123            4 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5124            4 :             if existing_initdb_timeline_id != timeline_id {
    5125            0 :                 let source_path = &remote_initdb_archive_path(
    5126            0 :                     &self.tenant_shard_id.tenant_id,
    5127            0 :                     &existing_initdb_timeline_id,
    5128            0 :                 );
    5129            0 :                 let dest_path =
    5130            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5131            0 : 
    5132            0 :                 // if this fails, it will get retried by retried control plane requests
    5133            0 :                 self.remote_storage
    5134            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5135            0 :                     .await
    5136            0 :                     .context("copy initdb tar")?;
    5137            4 :             }
    5138            4 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5139            4 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5140            4 :                     self.conf,
    5141            4 :                     &self.remote_storage,
    5142            4 :                     &self.tenant_shard_id,
    5143            4 :                     &existing_initdb_timeline_id,
    5144            4 :                     &self.cancel,
    5145            4 :                 )
    5146            4 :                 .await
    5147            4 :                 .context("download initdb tar")?;
    5148              : 
    5149            4 :             scopeguard::defer! {
    5150            4 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5151            4 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5152            4 :                 }
    5153            4 :             }
    5154            4 : 
    5155            4 :             let buf_read =
    5156            4 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5157            4 :             extract_zst_tarball(&pgdata_path, buf_read)
    5158            4 :                 .await
    5159            4 :                 .context("extract initdb tar")?;
    5160              :         } else {
    5161              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5162            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5163            0 :                 .await
    5164            0 :                 .context("run initdb")?;
    5165              : 
    5166              :             // Upload the created data dir to S3
    5167            0 :             if self.tenant_shard_id().is_shard_zero() {
    5168            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5169            0 :                     .await?;
    5170            0 :             }
    5171              :         }
    5172            4 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5173            4 : 
    5174            4 :         // Import the contents of the data directory at the initial checkpoint
    5175            4 :         // LSN, and any WAL after that.
    5176            4 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5177            4 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5178            4 :         let new_metadata = TimelineMetadata::new(
    5179            4 :             Lsn(0),
    5180            4 :             None,
    5181            4 :             None,
    5182            4 :             Lsn(0),
    5183            4 :             pgdata_lsn,
    5184            4 :             pgdata_lsn,
    5185            4 :             pg_version,
    5186            4 :         );
    5187            4 :         let (mut raw_timeline, timeline_ctx) = self
    5188            4 :             .prepare_new_timeline(
    5189            4 :                 timeline_id,
    5190            4 :                 &new_metadata,
    5191            4 :                 timeline_create_guard,
    5192            4 :                 pgdata_lsn,
    5193            4 :                 None,
    5194            4 :                 None,
    5195            4 :                 ctx,
    5196            4 :             )
    5197            4 :             .await?;
    5198              : 
    5199            4 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5200            4 :         raw_timeline
    5201            4 :             .write(|unfinished_timeline| async move {
    5202            4 :                 import_datadir::import_timeline_from_postgres_datadir(
    5203            4 :                     &unfinished_timeline,
    5204            4 :                     &pgdata_path,
    5205            4 :                     pgdata_lsn,
    5206            4 :                     &timeline_ctx,
    5207            4 :                 )
    5208            4 :                 .await
    5209            4 :                 .with_context(|| {
    5210            0 :                     format!(
    5211            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5212            0 :                     )
    5213            4 :                 })?;
    5214              : 
    5215            4 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5216            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5217            0 :                         "failpoint before-checkpoint-new-timeline"
    5218            0 :                     )))
    5219            4 :                 });
    5220              : 
    5221            4 :                 Ok(())
    5222            8 :             })
    5223            4 :             .await?;
    5224              : 
    5225              :         // All done!
    5226            4 :         let timeline = raw_timeline.finish_creation().await?;
    5227              : 
    5228              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5229              : 
    5230            4 :         Ok(CreateTimelineResult::Created(timeline))
    5231            4 :     }
    5232              : 
    5233          916 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5234          916 :         RemoteTimelineClient::new(
    5235          916 :             self.remote_storage.clone(),
    5236          916 :             self.deletion_queue_client.clone(),
    5237          916 :             self.conf,
    5238          916 :             self.tenant_shard_id,
    5239          916 :             timeline_id,
    5240          916 :             self.generation,
    5241          916 :             &self.tenant_conf.load().location,
    5242          916 :         )
    5243          916 :     }
    5244              : 
    5245              :     /// Builds required resources for a new timeline.
    5246          916 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5247          916 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5248          916 :         self.get_timeline_resources_for(remote_client)
    5249          916 :     }
    5250              : 
    5251              :     /// Builds timeline resources for the given remote client.
    5252          928 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5253          928 :         TimelineResources {
    5254          928 :             remote_client,
    5255          928 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5256          928 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5257          928 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5258          928 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5259          928 :         }
    5260          928 :     }
    5261              : 
    5262              :     /// Creates intermediate timeline structure and its files.
    5263              :     ///
    5264              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5265              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5266              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5267              :     #[allow(clippy::too_many_arguments)]
    5268          916 :     async fn prepare_new_timeline<'a>(
    5269          916 :         &'a self,
    5270          916 :         new_timeline_id: TimelineId,
    5271          916 :         new_metadata: &TimelineMetadata,
    5272          916 :         create_guard: TimelineCreateGuard,
    5273          916 :         start_lsn: Lsn,
    5274          916 :         ancestor: Option<Arc<Timeline>>,
    5275          916 :         rel_size_v2_status: Option<RelSizeMigration>,
    5276          916 :         ctx: &RequestContext,
    5277          916 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5278          916 :         let tenant_shard_id = self.tenant_shard_id;
    5279          916 : 
    5280          916 :         let resources = self.build_timeline_resources(new_timeline_id);
    5281          916 :         resources
    5282          916 :             .remote_client
    5283          916 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5284              : 
    5285          916 :         let (timeline_struct, timeline_ctx) = self
    5286          916 :             .create_timeline_struct(
    5287          916 :                 new_timeline_id,
    5288          916 :                 new_metadata,
    5289          916 :                 None,
    5290          916 :                 ancestor,
    5291          916 :                 resources,
    5292          916 :                 CreateTimelineCause::Load,
    5293          916 :                 create_guard.idempotency.clone(),
    5294          916 :                 None,
    5295          916 :                 rel_size_v2_status,
    5296          916 :                 ctx,
    5297          916 :             )
    5298          916 :             .context("Failed to create timeline data structure")?;
    5299              : 
    5300          916 :         timeline_struct.init_empty_layer_map(start_lsn);
    5301              : 
    5302          916 :         if let Err(e) = self
    5303          916 :             .create_timeline_files(&create_guard.timeline_path)
    5304          916 :             .await
    5305              :         {
    5306            0 :             error!(
    5307            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5308              :             );
    5309            0 :             cleanup_timeline_directory(create_guard);
    5310            0 :             return Err(e);
    5311          916 :         }
    5312          916 : 
    5313          916 :         debug!(
    5314            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5315              :         );
    5316              : 
    5317          916 :         Ok((
    5318          916 :             UninitializedTimeline::new(
    5319          916 :                 self,
    5320          916 :                 new_timeline_id,
    5321          916 :                 Some((timeline_struct, create_guard)),
    5322          916 :             ),
    5323          916 :             timeline_ctx,
    5324          916 :         ))
    5325          916 :     }
    5326              : 
    5327          916 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5328          916 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5329              : 
    5330          916 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5331            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5332          916 :         });
    5333              : 
    5334          916 :         Ok(())
    5335          916 :     }
    5336              : 
    5337              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5338              :     /// concurrent attempts to create the same timeline.
    5339              :     ///
    5340              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5341              :     /// offloaded timelines or not.
    5342          928 :     fn create_timeline_create_guard(
    5343          928 :         self: &Arc<Self>,
    5344          928 :         timeline_id: TimelineId,
    5345          928 :         idempotency: CreateTimelineIdempotency,
    5346          928 :         allow_offloaded: bool,
    5347          928 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5348          928 :         let tenant_shard_id = self.tenant_shard_id;
    5349          928 : 
    5350          928 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5351              : 
    5352          928 :         let create_guard = TimelineCreateGuard::new(
    5353          928 :             self,
    5354          928 :             timeline_id,
    5355          928 :             timeline_path.clone(),
    5356          928 :             idempotency,
    5357          928 :             allow_offloaded,
    5358          928 :         )?;
    5359              : 
    5360              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5361              :         // for creation.
    5362              :         // A timeline directory should never exist on disk already:
    5363              :         // - a previous failed creation would have cleaned up after itself
    5364              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5365              :         //
    5366              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5367              :         // this error may indicate a bug in cleanup on failed creations.
    5368          924 :         if timeline_path.exists() {
    5369            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5370            0 :                 "Timeline directory already exists! This is a bug."
    5371            0 :             )));
    5372          924 :         }
    5373          924 : 
    5374          924 :         Ok(create_guard)
    5375          928 :     }
    5376              : 
    5377              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5378              :     ///
    5379              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5380              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5381              :     pub async fn gather_size_inputs(
    5382              :         &self,
    5383              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5384              :         // (only if it is shorter than the real cutoff).
    5385              :         max_retention_period: Option<u64>,
    5386              :         cause: LogicalSizeCalculationCause,
    5387              :         cancel: &CancellationToken,
    5388              :         ctx: &RequestContext,
    5389              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5390              :         let logical_sizes_at_once = self
    5391              :             .conf
    5392              :             .concurrent_tenant_size_logical_size_queries
    5393              :             .inner();
    5394              : 
    5395              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5396              :         //
    5397              :         // But the only case where we need to run multiple of these at once is when we
    5398              :         // request a size for a tenant manually via API, while another background calculation
    5399              :         // is in progress (which is not a common case).
    5400              :         //
    5401              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5402              :         let mut shared_cache = tokio::select! {
    5403              :             locked = self.cached_logical_sizes.lock() => locked,
    5404              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5405              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5406              :         };
    5407              : 
    5408              :         size::gather_inputs(
    5409              :             self,
    5410              :             logical_sizes_at_once,
    5411              :             max_retention_period,
    5412              :             &mut shared_cache,
    5413              :             cause,
    5414              :             cancel,
    5415              :             ctx,
    5416              :         )
    5417              :         .await
    5418              :     }
    5419              : 
    5420              :     /// Calculate synthetic tenant size and cache the result.
    5421              :     /// This is periodically called by background worker.
    5422              :     /// result is cached in tenant struct
    5423              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5424              :     pub async fn calculate_synthetic_size(
    5425              :         &self,
    5426              :         cause: LogicalSizeCalculationCause,
    5427              :         cancel: &CancellationToken,
    5428              :         ctx: &RequestContext,
    5429              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5430              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5431              : 
    5432              :         let size = inputs.calculate();
    5433              : 
    5434              :         self.set_cached_synthetic_size(size);
    5435              : 
    5436              :         Ok(size)
    5437              :     }
    5438              : 
    5439              :     /// Cache given synthetic size and update the metric value
    5440            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5441            0 :         self.cached_synthetic_tenant_size
    5442            0 :             .store(size, Ordering::Relaxed);
    5443            0 : 
    5444            0 :         // Only shard zero should be calculating synthetic sizes
    5445            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5446              : 
    5447            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5448            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5449            0 :             .unwrap()
    5450            0 :             .set(size);
    5451            0 :     }
    5452              : 
    5453            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5454            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5455            0 :     }
    5456              : 
    5457              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5458              :     ///
    5459              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5460              :     /// from an external API handler.
    5461              :     ///
    5462              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5463              :     /// still bounded by tenant/timeline shutdown.
    5464              :     #[tracing::instrument(skip_all)]
    5465              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5466              :         let timelines = self.timelines.lock().unwrap().clone();
    5467              : 
    5468            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5469            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5470            0 :             timeline.freeze_and_flush().await?;
    5471            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5472            0 :             timeline.remote_client.wait_completion().await?;
    5473              : 
    5474            0 :             Ok(())
    5475            0 :         }
    5476              : 
    5477              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5478              :         // aborted when this function's future is cancelled: they should stay alive
    5479              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5480              :         // before Timeline shutdown completes.
    5481              :         let mut results = FuturesUnordered::new();
    5482              : 
    5483              :         for (_timeline_id, timeline) in timelines {
    5484              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5485              :             // means that if this function's future is cancelled, the Timeline shutdown
    5486              :             // will still wait for any I/O in here to complete.
    5487              :             let Ok(gate) = timeline.gate.enter() else {
    5488              :                 continue;
    5489              :             };
    5490            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5491              :             results.push(jh);
    5492              :         }
    5493              : 
    5494              :         while let Some(r) = results.next().await {
    5495              :             if let Err(e) = r {
    5496              :                 if !e.is_cancelled() && !e.is_panic() {
    5497              :                     tracing::error!("unexpected join error: {e:?}");
    5498              :                 }
    5499              :             }
    5500              :         }
    5501              : 
    5502              :         // The flushes we did above were just writes, but the Tenant might have had
    5503              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5504              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5505              :         // because it's typically a no-op.
    5506              :         match self.deletion_queue_client.flush_execute().await {
    5507              :             Ok(_) => {}
    5508              :             Err(DeletionQueueError::ShuttingDown) => {}
    5509              :         }
    5510              : 
    5511              :         Ok(())
    5512              :     }
    5513              : 
    5514            0 :     pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
    5515            0 :         self.tenant_conf.load().tenant_conf.clone()
    5516            0 :     }
    5517              : 
    5518              :     /// How much local storage would this tenant like to have?  It can cope with
    5519              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5520              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5521              :     /// by keeping important things on local disk.
    5522              :     ///
    5523              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5524              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5525              :     /// actually use more than they report here.
    5526            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5527            0 :         let timelines = self.timelines.lock().unwrap();
    5528            0 : 
    5529            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5530            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5531            0 :         // of them is used actively enough to occupy space on disk.
    5532            0 :         timelines
    5533            0 :             .values()
    5534            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5535            0 :             .max()
    5536            0 :             .unwrap_or(0)
    5537            0 :     }
    5538              : 
    5539              :     /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
    5540              :     /// manifest in `Self::remote_tenant_manifest`.
    5541              :     ///
    5542              :     /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
    5543              :     /// changing any `Tenant` state that's included in the manifest, consider making the manifest
    5544              :     /// the authoritative source of data with an API that automatically uploads on changes. Revisit
    5545              :     /// this when the manifest is more widely used and we have a better idea of the data model.
    5546          468 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5547              :         // Multiple tasks may call this function concurrently after mutating the Tenant runtime
    5548              :         // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
    5549              :         // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
    5550              :         // simple coalescing mechanism.
    5551          468 :         let mut guard = tokio::select! {
    5552          468 :             guard = self.remote_tenant_manifest.lock() => guard,
    5553          468 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5554              :         };
    5555              : 
    5556              :         // Build a new manifest.
    5557          468 :         let manifest = self.build_tenant_manifest();
    5558              : 
    5559              :         // Check if the manifest has changed. We ignore the version number here, to avoid
    5560              :         // uploading every manifest on version number bumps.
    5561          468 :         if let Some(old) = guard.as_ref() {
    5562           16 :             if manifest.eq_ignoring_version(old) {
    5563           12 :                 return Ok(());
    5564            4 :             }
    5565          452 :         }
    5566              : 
    5567              :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5568          456 :         match backoff::retry(
    5569          456 :             || async {
    5570          456 :                 upload_tenant_manifest(
    5571          456 :                     &self.remote_storage,
    5572          456 :                     &self.tenant_shard_id,
    5573          456 :                     self.generation,
    5574          456 :                     &manifest,
    5575          456 :                     &self.cancel,
    5576          456 :                 )
    5577          456 :                 .await
    5578          912 :             },
    5579          456 :             |_| self.cancel.is_cancelled(),
    5580          456 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5581          456 :             FAILED_REMOTE_OP_RETRIES,
    5582          456 :             "uploading tenant manifest",
    5583          456 :             &self.cancel,
    5584          456 :         )
    5585          456 :         .await
    5586              :         {
    5587            0 :             None => Err(TenantManifestError::Cancelled),
    5588            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5589            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5590              :             Some(Ok(_)) => {
    5591              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5592              :                 // re-uploading the same thing.
    5593          456 :                 *guard = Some(manifest);
    5594          456 : 
    5595          456 :                 Ok(())
    5596              :             }
    5597              :         }
    5598          468 :     }
    5599              : }
    5600              : 
    5601              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5602              : /// to get bootstrap data for timeline initialization.
    5603            0 : async fn run_initdb(
    5604            0 :     conf: &'static PageServerConf,
    5605            0 :     initdb_target_dir: &Utf8Path,
    5606            0 :     pg_version: u32,
    5607            0 :     cancel: &CancellationToken,
    5608            0 : ) -> Result<(), InitdbError> {
    5609            0 :     let initdb_bin_path = conf
    5610            0 :         .pg_bin_dir(pg_version)
    5611            0 :         .map_err(InitdbError::Other)?
    5612            0 :         .join("initdb");
    5613            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5614            0 :     info!(
    5615            0 :         "running {} in {}, libdir: {}",
    5616              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5617              :     );
    5618              : 
    5619            0 :     let _permit = {
    5620            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5621            0 :         INIT_DB_SEMAPHORE.acquire().await
    5622              :     };
    5623              : 
    5624            0 :     CONCURRENT_INITDBS.inc();
    5625            0 :     scopeguard::defer! {
    5626            0 :         CONCURRENT_INITDBS.dec();
    5627            0 :     }
    5628            0 : 
    5629            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5630            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5631            0 :         superuser: &conf.superuser,
    5632            0 :         locale: &conf.locale,
    5633            0 :         initdb_bin: &initdb_bin_path,
    5634            0 :         pg_version,
    5635            0 :         library_search_path: &initdb_lib_dir,
    5636            0 :         pgdata: initdb_target_dir,
    5637            0 :     })
    5638            0 :     .await
    5639            0 :     .map_err(InitdbError::Inner);
    5640            0 : 
    5641            0 :     // This isn't true cancellation support, see above. Still return an error to
    5642            0 :     // excercise the cancellation code path.
    5643            0 :     if cancel.is_cancelled() {
    5644            0 :         return Err(InitdbError::Cancelled);
    5645            0 :     }
    5646            0 : 
    5647            0 :     res
    5648            0 : }
    5649              : 
    5650              : /// Dump contents of a layer file to stdout.
    5651            0 : pub async fn dump_layerfile_from_path(
    5652            0 :     path: &Utf8Path,
    5653            0 :     verbose: bool,
    5654            0 :     ctx: &RequestContext,
    5655            0 : ) -> anyhow::Result<()> {
    5656              :     use std::os::unix::fs::FileExt;
    5657              : 
    5658              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5659              :     // file.
    5660            0 :     let file = File::open(path)?;
    5661            0 :     let mut header_buf = [0u8; 2];
    5662            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5663              : 
    5664            0 :     match u16::from_be_bytes(header_buf) {
    5665              :         crate::IMAGE_FILE_MAGIC => {
    5666            0 :             ImageLayer::new_for_path(path, file)?
    5667            0 :                 .dump(verbose, ctx)
    5668            0 :                 .await?
    5669              :         }
    5670              :         crate::DELTA_FILE_MAGIC => {
    5671            0 :             DeltaLayer::new_for_path(path, file)?
    5672            0 :                 .dump(verbose, ctx)
    5673            0 :                 .await?
    5674              :         }
    5675            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5676              :     }
    5677              : 
    5678            0 :     Ok(())
    5679            0 : }
    5680              : 
    5681              : #[cfg(test)]
    5682              : pub(crate) mod harness {
    5683              :     use bytes::{Bytes, BytesMut};
    5684              :     use hex_literal::hex;
    5685              :     use once_cell::sync::OnceCell;
    5686              :     use pageserver_api::key::Key;
    5687              :     use pageserver_api::models::ShardParameters;
    5688              :     use pageserver_api::record::NeonWalRecord;
    5689              :     use pageserver_api::shard::ShardIndex;
    5690              :     use utils::id::TenantId;
    5691              :     use utils::logging;
    5692              : 
    5693              :     use super::*;
    5694              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5695              :     use crate::l0_flush::L0FlushConfig;
    5696              :     use crate::walredo::apply_neon;
    5697              : 
    5698              :     pub const TIMELINE_ID: TimelineId =
    5699              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5700              :     pub const NEW_TIMELINE_ID: TimelineId =
    5701              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5702              : 
    5703              :     /// Convenience function to create a page image with given string as the only content
    5704     10057521 :     pub fn test_img(s: &str) -> Bytes {
    5705     10057521 :         let mut buf = BytesMut::new();
    5706     10057521 :         buf.extend_from_slice(s.as_bytes());
    5707     10057521 :         buf.resize(64, 0);
    5708     10057521 : 
    5709     10057521 :         buf.freeze()
    5710     10057521 :     }
    5711              : 
    5712              :     pub struct TenantHarness {
    5713              :         pub conf: &'static PageServerConf,
    5714              :         pub tenant_conf: pageserver_api::models::TenantConfig,
    5715              :         pub tenant_shard_id: TenantShardId,
    5716              :         pub generation: Generation,
    5717              :         pub shard: ShardIndex,
    5718              :         pub remote_storage: GenericRemoteStorage,
    5719              :         pub remote_fs_dir: Utf8PathBuf,
    5720              :         pub deletion_queue: MockDeletionQueue,
    5721              :     }
    5722              : 
    5723              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5724              : 
    5725          512 :     pub(crate) fn setup_logging() {
    5726          512 :         LOG_HANDLE.get_or_init(|| {
    5727          488 :             logging::init(
    5728          488 :                 logging::LogFormat::Test,
    5729          488 :                 // enable it in case the tests exercise code paths that use
    5730          488 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5731          488 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5732          488 :                 logging::Output::Stdout,
    5733          488 :             )
    5734          488 :             .expect("Failed to init test logging");
    5735          512 :         });
    5736          512 :     }
    5737              : 
    5738              :     impl TenantHarness {
    5739          464 :         pub async fn create_custom(
    5740          464 :             test_name: &'static str,
    5741          464 :             tenant_conf: pageserver_api::models::TenantConfig,
    5742          464 :             tenant_id: TenantId,
    5743          464 :             shard_identity: ShardIdentity,
    5744          464 :             generation: Generation,
    5745          464 :         ) -> anyhow::Result<Self> {
    5746          464 :             setup_logging();
    5747          464 : 
    5748          464 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5749          464 :             let _ = fs::remove_dir_all(&repo_dir);
    5750          464 :             fs::create_dir_all(&repo_dir)?;
    5751              : 
    5752          464 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5753          464 :             // Make a static copy of the config. This can never be free'd, but that's
    5754          464 :             // OK in a test.
    5755          464 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5756          464 : 
    5757          464 :             let shard = shard_identity.shard_index();
    5758          464 :             let tenant_shard_id = TenantShardId {
    5759          464 :                 tenant_id,
    5760          464 :                 shard_number: shard.shard_number,
    5761          464 :                 shard_count: shard.shard_count,
    5762          464 :             };
    5763          464 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5764          464 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5765              : 
    5766              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5767          464 :             let remote_fs_dir = conf.workdir.join("localfs");
    5768          464 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5769          464 :             let config = RemoteStorageConfig {
    5770          464 :                 storage: RemoteStorageKind::LocalFs {
    5771          464 :                     local_path: remote_fs_dir.clone(),
    5772          464 :                 },
    5773          464 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5774          464 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5775          464 :             };
    5776          464 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5777          464 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5778          464 : 
    5779          464 :             Ok(Self {
    5780          464 :                 conf,
    5781          464 :                 tenant_conf,
    5782          464 :                 tenant_shard_id,
    5783          464 :                 generation,
    5784          464 :                 shard,
    5785          464 :                 remote_storage,
    5786          464 :                 remote_fs_dir,
    5787          464 :                 deletion_queue,
    5788          464 :             })
    5789          464 :         }
    5790              : 
    5791          436 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5792          436 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5793          436 :             // The tests perform them manually if needed.
    5794          436 :             let tenant_conf = pageserver_api::models::TenantConfig {
    5795          436 :                 gc_period: Some(Duration::ZERO),
    5796          436 :                 compaction_period: Some(Duration::ZERO),
    5797          436 :                 ..Default::default()
    5798          436 :             };
    5799          436 :             let tenant_id = TenantId::generate();
    5800          436 :             let shard = ShardIdentity::unsharded();
    5801          436 :             Self::create_custom(
    5802          436 :                 test_name,
    5803          436 :                 tenant_conf,
    5804          436 :                 tenant_id,
    5805          436 :                 shard,
    5806          436 :                 Generation::new(0xdeadbeef),
    5807          436 :             )
    5808          436 :             .await
    5809          436 :         }
    5810              : 
    5811           40 :         pub fn span(&self) -> tracing::Span {
    5812           40 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5813           40 :         }
    5814              : 
    5815          464 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5816          464 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    5817          464 :                 .with_scope_unit_test();
    5818          464 :             (
    5819          464 :                 self.do_try_load(&ctx)
    5820          464 :                     .await
    5821          464 :                     .expect("failed to load test tenant"),
    5822          464 :                 ctx,
    5823          464 :             )
    5824          464 :         }
    5825              : 
    5826              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5827              :         pub(crate) async fn do_try_load(
    5828              :             &self,
    5829              :             ctx: &RequestContext,
    5830              :         ) -> anyhow::Result<Arc<Tenant>> {
    5831              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5832              : 
    5833              :             let tenant = Arc::new(Tenant::new(
    5834              :                 TenantState::Attaching,
    5835              :                 self.conf,
    5836              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5837              :                     self.tenant_conf.clone(),
    5838              :                     self.generation,
    5839              :                     &ShardParameters::default(),
    5840              :                 ))
    5841              :                 .unwrap(),
    5842              :                 // This is a legacy/test code path: sharding isn't supported here.
    5843              :                 ShardIdentity::unsharded(),
    5844              :                 Some(walredo_mgr),
    5845              :                 self.tenant_shard_id,
    5846              :                 self.remote_storage.clone(),
    5847              :                 self.deletion_queue.new_client(),
    5848              :                 // TODO: ideally we should run all unit tests with both configs
    5849              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5850              :             ));
    5851              : 
    5852              :             let preload = tenant
    5853              :                 .preload(&self.remote_storage, CancellationToken::new())
    5854              :                 .await?;
    5855              :             tenant.attach(Some(preload), ctx).await?;
    5856              : 
    5857              :             tenant.state.send_replace(TenantState::Active);
    5858              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5859              :                 timeline.set_state(TimelineState::Active);
    5860              :             }
    5861              :             Ok(tenant)
    5862              :         }
    5863              : 
    5864            4 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5865            4 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5866            4 :         }
    5867              :     }
    5868              : 
    5869              :     // Mock WAL redo manager that doesn't do much
    5870              :     pub(crate) struct TestRedoManager;
    5871              : 
    5872              :     impl TestRedoManager {
    5873              :         /// # Cancel-Safety
    5874              :         ///
    5875              :         /// This method is cancellation-safe.
    5876       107096 :         pub async fn request_redo(
    5877       107096 :             &self,
    5878       107096 :             key: Key,
    5879       107096 :             lsn: Lsn,
    5880       107096 :             base_img: Option<(Lsn, Bytes)>,
    5881       107096 :             records: Vec<(Lsn, NeonWalRecord)>,
    5882       107096 :             _pg_version: u32,
    5883       107096 :             _redo_attempt_type: RedoAttemptType,
    5884       107096 :         ) -> Result<Bytes, walredo::Error> {
    5885      5614040 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5886       107096 :             if records_neon {
    5887              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5888       107096 :                 let mut page = match (base_img, records.first()) {
    5889        52116 :                     (Some((_lsn, img)), _) => {
    5890        52116 :                         let mut page = BytesMut::new();
    5891        52116 :                         page.extend_from_slice(&img);
    5892        52116 :                         page
    5893              :                     }
    5894        54980 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5895              :                     _ => {
    5896            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5897              :                     }
    5898              :                 };
    5899              : 
    5900      5721132 :                 for (record_lsn, record) in records {
    5901      5614040 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5902              :                 }
    5903       107092 :                 Ok(page.freeze())
    5904              :             } else {
    5905              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5906            0 :                 let s = format!(
    5907            0 :                     "redo for {} to get to {}, with {} and {} records",
    5908            0 :                     key,
    5909            0 :                     lsn,
    5910            0 :                     if base_img.is_some() {
    5911            0 :                         "base image"
    5912              :                     } else {
    5913            0 :                         "no base image"
    5914              :                     },
    5915            0 :                     records.len()
    5916            0 :                 );
    5917            0 :                 println!("{s}");
    5918            0 : 
    5919            0 :                 Ok(test_img(&s))
    5920              :             }
    5921       107096 :         }
    5922              :     }
    5923              : }
    5924              : 
    5925              : #[cfg(test)]
    5926              : mod tests {
    5927              :     use std::collections::{BTreeMap, BTreeSet};
    5928              : 
    5929              :     use bytes::{Bytes, BytesMut};
    5930              :     use hex_literal::hex;
    5931              :     use itertools::Itertools;
    5932              :     #[cfg(feature = "testing")]
    5933              :     use models::CompactLsnRange;
    5934              :     use pageserver_api::key::{AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
    5935              :     use pageserver_api::keyspace::KeySpace;
    5936              :     #[cfg(feature = "testing")]
    5937              :     use pageserver_api::keyspace::KeySpaceRandomAccum;
    5938              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5939              :     #[cfg(feature = "testing")]
    5940              :     use pageserver_api::record::NeonWalRecord;
    5941              :     use pageserver_api::value::Value;
    5942              :     use pageserver_compaction::helpers::overlaps_with;
    5943              :     #[cfg(feature = "testing")]
    5944              :     use rand::SeedableRng;
    5945              :     #[cfg(feature = "testing")]
    5946              :     use rand::rngs::StdRng;
    5947              :     use rand::{Rng, thread_rng};
    5948              :     #[cfg(feature = "testing")]
    5949              :     use std::ops::Range;
    5950              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5951              :     use tests::storage_layer::ValuesReconstructState;
    5952              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5953              :     #[cfg(feature = "testing")]
    5954              :     use timeline::GcInfo;
    5955              :     #[cfg(feature = "testing")]
    5956              :     use timeline::InMemoryLayerTestDesc;
    5957              :     #[cfg(feature = "testing")]
    5958              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5959              :     use timeline::{CompactOptions, DeltaLayerTestDesc, VersionedKeySpaceQuery};
    5960              :     use utils::id::TenantId;
    5961              : 
    5962              :     use super::*;
    5963              :     use crate::DEFAULT_PG_VERSION;
    5964              :     use crate::keyspace::KeySpaceAccum;
    5965              :     use crate::tenant::harness::*;
    5966              :     use crate::tenant::timeline::CompactFlags;
    5967              : 
    5968              :     static TEST_KEY: Lazy<Key> =
    5969           36 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5970              : 
    5971              :     #[cfg(feature = "testing")]
    5972              :     struct TestTimelineSpecification {
    5973              :         start_lsn: Lsn,
    5974              :         last_record_lsn: Lsn,
    5975              : 
    5976              :         in_memory_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    5977              :         delta_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    5978              :         image_layers_shape: Vec<(Range<Key>, Lsn)>,
    5979              : 
    5980              :         gap_chance: u8,
    5981              :         will_init_chance: u8,
    5982              :     }
    5983              : 
    5984              :     #[cfg(feature = "testing")]
    5985              :     struct Storage {
    5986              :         storage: HashMap<(Key, Lsn), Value>,
    5987              :         start_lsn: Lsn,
    5988              :     }
    5989              : 
    5990              :     #[cfg(feature = "testing")]
    5991              :     impl Storage {
    5992       128000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    5993              :             use bytes::BufMut;
    5994              : 
    5995       128000 :             let mut crnt_lsn = lsn;
    5996       128000 :             let mut got_base = false;
    5997       128000 : 
    5998       128000 :             let mut acc = Vec::new();
    5999              : 
    6000     11327484 :             while crnt_lsn >= self.start_lsn {
    6001     11327484 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6002      5684688 :                     acc.push(value.clone());
    6003              : 
    6004      5611524 :                     match value {
    6005      5611524 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6006      5611524 :                             if *will_init {
    6007        54836 :                                 got_base = true;
    6008        54836 :                                 break;
    6009      5556688 :                             }
    6010              :                         }
    6011              :                         Value::Image(_) => {
    6012        73164 :                             got_base = true;
    6013        73164 :                             break;
    6014              :                         }
    6015            0 :                         _ => unreachable!(),
    6016              :                     }
    6017      5642796 :                 }
    6018              : 
    6019     11199484 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6020              :             }
    6021              : 
    6022       128000 :             assert!(
    6023       128000 :                 got_base,
    6024            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6025              :             );
    6026              : 
    6027       128000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6028              : 
    6029       128000 :             let mut blob = BytesMut::new();
    6030      5684688 :             for value in acc.into_iter().rev() {
    6031      5611524 :                 match value {
    6032      5611524 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6033      5611524 :                         blob.extend_from_slice(append.as_bytes());
    6034      5611524 :                     }
    6035        73164 :                     Value::Image(img) => {
    6036        73164 :                         blob.put(img);
    6037        73164 :                     }
    6038            0 :                     _ => unreachable!(),
    6039              :                 }
    6040              :             }
    6041              : 
    6042       128000 :             blob.into()
    6043       128000 :         }
    6044              :     }
    6045              : 
    6046              :     #[cfg(feature = "testing")]
    6047              :     #[allow(clippy::too_many_arguments)]
    6048            4 :     async fn randomize_timeline(
    6049            4 :         tenant: &Arc<Tenant>,
    6050            4 :         new_timeline_id: TimelineId,
    6051            4 :         pg_version: u32,
    6052            4 :         spec: TestTimelineSpecification,
    6053            4 :         random: &mut rand::rngs::StdRng,
    6054            4 :         ctx: &RequestContext,
    6055            4 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6056            4 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6057            4 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6058              : 
    6059            8 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6060            8 :             let mut lsn = lsn_range.start;
    6061          808 :             while lsn < lsn_range.end {
    6062          800 :                 let mut key = key_range.start;
    6063        84072 :                 while key < key_range.end {
    6064        83272 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6065        83272 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6066        83272 : 
    6067        83272 :                     if gap {
    6068         4072 :                         continue;
    6069        79200 :                     }
    6070              : 
    6071        79200 :                     let record = if will_init {
    6072          764 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6073              :                     } else {
    6074        78436 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6075              :                     };
    6076              : 
    6077        79200 :                     storage.insert((key, lsn), record);
    6078        79200 : 
    6079        79200 :                     key = key.next();
    6080              :                 }
    6081          800 :                 lsn = Lsn(lsn.0 + 1);
    6082              :             }
    6083              : 
    6084              :             // Stash some interesting LSN for future use
    6085           24 :             for offset in [0, 5, 100].iter() {
    6086           24 :                 if *offset == 0 {
    6087            8 :                     interesting_lsns.push(lsn_range.start);
    6088            8 :                 } else {
    6089           16 :                     let below = lsn_range.start.checked_sub(*offset);
    6090           16 :                     match below {
    6091           16 :                         Some(v) if v >= spec.start_lsn => {
    6092           16 :                             interesting_lsns.push(v);
    6093           16 :                         }
    6094            0 :                         _ => {}
    6095              :                     }
    6096              : 
    6097           16 :                     let above = Lsn(lsn_range.start.0 + offset);
    6098           16 :                     interesting_lsns.push(above);
    6099              :                 }
    6100              :             }
    6101              :         }
    6102              : 
    6103           12 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6104           12 :             let mut lsn = lsn_range.start;
    6105         1260 :             while lsn < lsn_range.end {
    6106         1248 :                 let mut key = key_range.start;
    6107        44448 :                 while key < key_range.end {
    6108        43200 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6109        43200 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6110        43200 : 
    6111        43200 :                     if gap {
    6112         2016 :                         continue;
    6113        41184 :                     }
    6114              : 
    6115        41184 :                     let record = if will_init {
    6116          412 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6117              :                     } else {
    6118        40772 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6119              :                     };
    6120              : 
    6121        41184 :                     storage.insert((key, lsn), record);
    6122        41184 : 
    6123        41184 :                     key = key.next();
    6124              :                 }
    6125         1248 :                 lsn = Lsn(lsn.0 + 1);
    6126              :             }
    6127              : 
    6128              :             // Stash some interesting LSN for future use
    6129           36 :             for offset in [0, 5, 100].iter() {
    6130           36 :                 if *offset == 0 {
    6131           12 :                     interesting_lsns.push(lsn_range.start);
    6132           12 :                 } else {
    6133           24 :                     let below = lsn_range.start.checked_sub(*offset);
    6134           24 :                     match below {
    6135           24 :                         Some(v) if v >= spec.start_lsn => {
    6136           12 :                             interesting_lsns.push(v);
    6137           12 :                         }
    6138           12 :                         _ => {}
    6139              :                     }
    6140              : 
    6141           24 :                     let above = Lsn(lsn_range.start.0 + offset);
    6142           24 :                     interesting_lsns.push(above);
    6143              :                 }
    6144              :             }
    6145              :         }
    6146              : 
    6147           12 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6148           12 :             let mut key = key_range.start;
    6149          568 :             while key < key_range.end {
    6150          556 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6151          556 :                 let record = Value::Image(blob.clone());
    6152          556 :                 storage.insert((key, *lsn), record);
    6153          556 : 
    6154          556 :                 key = key.next();
    6155          556 :             }
    6156              : 
    6157              :             // Stash some interesting LSN for future use
    6158           36 :             for offset in [0, 5, 100].iter() {
    6159           36 :                 if *offset == 0 {
    6160           12 :                     interesting_lsns.push(*lsn);
    6161           12 :                 } else {
    6162           24 :                     let below = lsn.checked_sub(*offset);
    6163           24 :                     match below {
    6164           24 :                         Some(v) if v >= spec.start_lsn => {
    6165           16 :                             interesting_lsns.push(v);
    6166           16 :                         }
    6167            8 :                         _ => {}
    6168              :                     }
    6169              : 
    6170           24 :                     let above = Lsn(lsn.0 + offset);
    6171           24 :                     interesting_lsns.push(above);
    6172              :                 }
    6173              :             }
    6174              :         }
    6175              : 
    6176            4 :         let in_memory_test_layers = {
    6177            4 :             let mut acc = Vec::new();
    6178              : 
    6179            8 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6180            8 :                 let mut data = Vec::new();
    6181            8 : 
    6182            8 :                 let mut lsn = lsn_range.start;
    6183          808 :                 while lsn < lsn_range.end {
    6184          800 :                     let mut key = key_range.start;
    6185        80000 :                     while key < key_range.end {
    6186        79200 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6187        79200 :                             data.push((key, lsn, record.clone()));
    6188        79200 :                         }
    6189              : 
    6190        79200 :                         key = key.next();
    6191              :                     }
    6192          800 :                     lsn = Lsn(lsn.0 + 1);
    6193              :                 }
    6194              : 
    6195            8 :                 acc.push(InMemoryLayerTestDesc {
    6196            8 :                     data,
    6197            8 :                     lsn_range: lsn_range.clone(),
    6198            8 :                     is_open: false,
    6199            8 :                 })
    6200              :             }
    6201              : 
    6202            4 :             acc
    6203              :         };
    6204              : 
    6205            4 :         let delta_test_layers = {
    6206            4 :             let mut acc = Vec::new();
    6207              : 
    6208           12 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6209           12 :                 let mut data = Vec::new();
    6210           12 : 
    6211           12 :                 let mut lsn = lsn_range.start;
    6212         1260 :                 while lsn < lsn_range.end {
    6213         1248 :                     let mut key = key_range.start;
    6214        42432 :                     while key < key_range.end {
    6215        41184 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6216        41184 :                             data.push((key, lsn, record.clone()));
    6217        41184 :                         }
    6218              : 
    6219        41184 :                         key = key.next();
    6220              :                     }
    6221         1248 :                     lsn = Lsn(lsn.0 + 1);
    6222              :                 }
    6223              : 
    6224           12 :                 acc.push(DeltaLayerTestDesc {
    6225           12 :                     data,
    6226           12 :                     lsn_range: lsn_range.clone(),
    6227           12 :                     key_range: key_range.clone(),
    6228           12 :                 })
    6229              :             }
    6230              : 
    6231            4 :             acc
    6232              :         };
    6233              : 
    6234            4 :         let image_test_layers = {
    6235            4 :             let mut acc = Vec::new();
    6236              : 
    6237           12 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6238           12 :                 let mut data = Vec::new();
    6239           12 : 
    6240           12 :                 let mut key = key_range.start;
    6241          568 :                 while key < key_range.end {
    6242          556 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6243          556 :                         let blob = match record {
    6244          556 :                             Value::Image(blob) => blob.clone(),
    6245            0 :                             _ => unreachable!(),
    6246              :                         };
    6247              : 
    6248          556 :                         data.push((key, blob));
    6249            0 :                     }
    6250              : 
    6251          556 :                     key = key.next();
    6252              :                 }
    6253              : 
    6254           12 :                 acc.push((*lsn, data));
    6255              :             }
    6256              : 
    6257            4 :             acc
    6258              :         };
    6259              : 
    6260            4 :         let tline = tenant
    6261            4 :             .create_test_timeline_with_layers(
    6262            4 :                 new_timeline_id,
    6263            4 :                 spec.start_lsn,
    6264            4 :                 pg_version,
    6265            4 :                 ctx,
    6266            4 :                 in_memory_test_layers,
    6267            4 :                 delta_test_layers,
    6268            4 :                 image_test_layers,
    6269            4 :                 spec.last_record_lsn,
    6270            4 :             )
    6271            4 :             .await?;
    6272              : 
    6273            4 :         Ok((
    6274            4 :             tline,
    6275            4 :             Storage {
    6276            4 :                 storage,
    6277            4 :                 start_lsn: spec.start_lsn,
    6278            4 :             },
    6279            4 :             interesting_lsns,
    6280            4 :         ))
    6281            4 :     }
    6282              : 
    6283              :     #[tokio::test]
    6284            4 :     async fn test_basic() -> anyhow::Result<()> {
    6285            4 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6286            4 :         let tline = tenant
    6287            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6288            4 :             .await?;
    6289            4 : 
    6290            4 :         let mut writer = tline.writer().await;
    6291            4 :         writer
    6292            4 :             .put(
    6293            4 :                 *TEST_KEY,
    6294            4 :                 Lsn(0x10),
    6295            4 :                 &Value::Image(test_img("foo at 0x10")),
    6296            4 :                 &ctx,
    6297            4 :             )
    6298            4 :             .await?;
    6299            4 :         writer.finish_write(Lsn(0x10));
    6300            4 :         drop(writer);
    6301            4 : 
    6302            4 :         let mut writer = tline.writer().await;
    6303            4 :         writer
    6304            4 :             .put(
    6305            4 :                 *TEST_KEY,
    6306            4 :                 Lsn(0x20),
    6307            4 :                 &Value::Image(test_img("foo at 0x20")),
    6308            4 :                 &ctx,
    6309            4 :             )
    6310            4 :             .await?;
    6311            4 :         writer.finish_write(Lsn(0x20));
    6312            4 :         drop(writer);
    6313            4 : 
    6314            4 :         assert_eq!(
    6315            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6316            4 :             test_img("foo at 0x10")
    6317            4 :         );
    6318            4 :         assert_eq!(
    6319            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6320            4 :             test_img("foo at 0x10")
    6321            4 :         );
    6322            4 :         assert_eq!(
    6323            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6324            4 :             test_img("foo at 0x20")
    6325            4 :         );
    6326            4 : 
    6327            4 :         Ok(())
    6328            4 :     }
    6329              : 
    6330              :     #[tokio::test]
    6331            4 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6332            4 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6333            4 :             .await?
    6334            4 :             .load()
    6335            4 :             .await;
    6336            4 :         let _ = tenant
    6337            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6338            4 :             .await?;
    6339            4 : 
    6340            4 :         match tenant
    6341            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6342            4 :             .await
    6343            4 :         {
    6344            4 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6345            4 :             Err(e) => assert_eq!(
    6346            4 :                 e.to_string(),
    6347            4 :                 "timeline already exists with different parameters".to_string()
    6348            4 :             ),
    6349            4 :         }
    6350            4 : 
    6351            4 :         Ok(())
    6352            4 :     }
    6353              : 
    6354              :     /// Convenience function to create a page image with given string as the only content
    6355           20 :     pub fn test_value(s: &str) -> Value {
    6356           20 :         let mut buf = BytesMut::new();
    6357           20 :         buf.extend_from_slice(s.as_bytes());
    6358           20 :         Value::Image(buf.freeze())
    6359           20 :     }
    6360              : 
    6361              :     ///
    6362              :     /// Test branch creation
    6363              :     ///
    6364              :     #[tokio::test]
    6365            4 :     async fn test_branch() -> anyhow::Result<()> {
    6366            4 :         use std::str::from_utf8;
    6367            4 : 
    6368            4 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6369            4 :         let tline = tenant
    6370            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6371            4 :             .await?;
    6372            4 :         let mut writer = tline.writer().await;
    6373            4 : 
    6374            4 :         #[allow(non_snake_case)]
    6375            4 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6376            4 :         #[allow(non_snake_case)]
    6377            4 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6378            4 : 
    6379            4 :         // Insert a value on the timeline
    6380            4 :         writer
    6381            4 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6382            4 :             .await?;
    6383            4 :         writer
    6384            4 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6385            4 :             .await?;
    6386            4 :         writer.finish_write(Lsn(0x20));
    6387            4 : 
    6388            4 :         writer
    6389            4 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6390            4 :             .await?;
    6391            4 :         writer.finish_write(Lsn(0x30));
    6392            4 :         writer
    6393            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6394            4 :             .await?;
    6395            4 :         writer.finish_write(Lsn(0x40));
    6396            4 : 
    6397            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6398            4 : 
    6399            4 :         // Branch the history, modify relation differently on the new timeline
    6400            4 :         tenant
    6401            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6402            4 :             .await?;
    6403            4 :         let newtline = tenant
    6404            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6405            4 :             .expect("Should have a local timeline");
    6406            4 :         let mut new_writer = newtline.writer().await;
    6407            4 :         new_writer
    6408            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6409            4 :             .await?;
    6410            4 :         new_writer.finish_write(Lsn(0x40));
    6411            4 : 
    6412            4 :         // Check page contents on both branches
    6413            4 :         assert_eq!(
    6414            4 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6415            4 :             "foo at 0x40"
    6416            4 :         );
    6417            4 :         assert_eq!(
    6418            4 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6419            4 :             "bar at 0x40"
    6420            4 :         );
    6421            4 :         assert_eq!(
    6422            4 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6423            4 :             "foobar at 0x20"
    6424            4 :         );
    6425            4 : 
    6426            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6427            4 : 
    6428            4 :         Ok(())
    6429            4 :     }
    6430              : 
    6431           40 :     async fn make_some_layers(
    6432           40 :         tline: &Timeline,
    6433           40 :         start_lsn: Lsn,
    6434           40 :         ctx: &RequestContext,
    6435           40 :     ) -> anyhow::Result<()> {
    6436           40 :         let mut lsn = start_lsn;
    6437              :         {
    6438           40 :             let mut writer = tline.writer().await;
    6439              :             // Create a relation on the timeline
    6440           40 :             writer
    6441           40 :                 .put(
    6442           40 :                     *TEST_KEY,
    6443           40 :                     lsn,
    6444           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6445           40 :                     ctx,
    6446           40 :                 )
    6447           40 :                 .await?;
    6448           40 :             writer.finish_write(lsn);
    6449           40 :             lsn += 0x10;
    6450           40 :             writer
    6451           40 :                 .put(
    6452           40 :                     *TEST_KEY,
    6453           40 :                     lsn,
    6454           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6455           40 :                     ctx,
    6456           40 :                 )
    6457           40 :                 .await?;
    6458           40 :             writer.finish_write(lsn);
    6459           40 :             lsn += 0x10;
    6460           40 :         }
    6461           40 :         tline.freeze_and_flush().await?;
    6462              :         {
    6463           40 :             let mut writer = tline.writer().await;
    6464           40 :             writer
    6465           40 :                 .put(
    6466           40 :                     *TEST_KEY,
    6467           40 :                     lsn,
    6468           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6469           40 :                     ctx,
    6470           40 :                 )
    6471           40 :                 .await?;
    6472           40 :             writer.finish_write(lsn);
    6473           40 :             lsn += 0x10;
    6474           40 :             writer
    6475           40 :                 .put(
    6476           40 :                     *TEST_KEY,
    6477           40 :                     lsn,
    6478           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6479           40 :                     ctx,
    6480           40 :                 )
    6481           40 :                 .await?;
    6482           40 :             writer.finish_write(lsn);
    6483           40 :         }
    6484           40 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6485           40 :     }
    6486              : 
    6487              :     #[tokio::test(start_paused = true)]
    6488            4 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6489            4 :         let (tenant, ctx) =
    6490            4 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6491            4 :                 .await?
    6492            4 :                 .load()
    6493            4 :                 .await;
    6494            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6495            4 :         // initial transition into AttachedSingle.
    6496            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6497            4 :         tokio::time::resume();
    6498            4 :         let tline = tenant
    6499            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6500            4 :             .await?;
    6501            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6502            4 : 
    6503            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6504            4 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6505            4 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6506            4 :         // below should fail.
    6507            4 :         tenant
    6508            4 :             .gc_iteration(
    6509            4 :                 Some(TIMELINE_ID),
    6510            4 :                 0x10,
    6511            4 :                 Duration::ZERO,
    6512            4 :                 &CancellationToken::new(),
    6513            4 :                 &ctx,
    6514            4 :             )
    6515            4 :             .await?;
    6516            4 : 
    6517            4 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6518            4 :         match tenant
    6519            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6520            4 :             .await
    6521            4 :         {
    6522            4 :             Ok(_) => panic!("branching should have failed"),
    6523            4 :             Err(err) => {
    6524            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6525            4 :                     panic!("wrong error type")
    6526            4 :                 };
    6527            4 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6528            4 :                 assert!(
    6529            4 :                     err.source()
    6530            4 :                         .unwrap()
    6531            4 :                         .to_string()
    6532            4 :                         .contains("we might've already garbage collected needed data")
    6533            4 :                 )
    6534            4 :             }
    6535            4 :         }
    6536            4 : 
    6537            4 :         Ok(())
    6538            4 :     }
    6539              : 
    6540              :     #[tokio::test]
    6541            4 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6542            4 :         let (tenant, ctx) =
    6543            4 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6544            4 :                 .await?
    6545            4 :                 .load()
    6546            4 :                 .await;
    6547            4 : 
    6548            4 :         let tline = tenant
    6549            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6550            4 :             .await?;
    6551            4 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6552            4 :         match tenant
    6553            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6554            4 :             .await
    6555            4 :         {
    6556            4 :             Ok(_) => panic!("branching should have failed"),
    6557            4 :             Err(err) => {
    6558            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6559            4 :                     panic!("wrong error type");
    6560            4 :                 };
    6561            4 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6562            4 :                 assert!(
    6563            4 :                     &err.source()
    6564            4 :                         .unwrap()
    6565            4 :                         .to_string()
    6566            4 :                         .contains("is earlier than latest GC cutoff")
    6567            4 :                 );
    6568            4 :             }
    6569            4 :         }
    6570            4 : 
    6571            4 :         Ok(())
    6572            4 :     }
    6573              : 
    6574              :     /*
    6575              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6576              :     // remove the old value, we'd need to work a little harder
    6577              :     #[tokio::test]
    6578              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6579              :         let repo =
    6580              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6581              :             .load();
    6582              : 
    6583              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6584              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6585              : 
    6586              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6587              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6588              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6589              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6590              :             Ok(_) => panic!("request for page should have failed"),
    6591              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6592              :         }
    6593              :         Ok(())
    6594              :     }
    6595              :      */
    6596              : 
    6597              :     #[tokio::test]
    6598            4 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6599            4 :         let (tenant, ctx) =
    6600            4 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6601            4 :                 .await?
    6602            4 :                 .load()
    6603            4 :                 .await;
    6604            4 :         let tline = tenant
    6605            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6606            4 :             .await?;
    6607            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6608            4 : 
    6609            4 :         tenant
    6610            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6611            4 :             .await?;
    6612            4 :         let newtline = tenant
    6613            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6614            4 :             .expect("Should have a local timeline");
    6615            4 : 
    6616            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6617            4 : 
    6618            4 :         tline.set_broken("test".to_owned());
    6619            4 : 
    6620            4 :         tenant
    6621            4 :             .gc_iteration(
    6622            4 :                 Some(TIMELINE_ID),
    6623            4 :                 0x10,
    6624            4 :                 Duration::ZERO,
    6625            4 :                 &CancellationToken::new(),
    6626            4 :                 &ctx,
    6627            4 :             )
    6628            4 :             .await?;
    6629            4 : 
    6630            4 :         // The branchpoints should contain all timelines, even ones marked
    6631            4 :         // as Broken.
    6632            4 :         {
    6633            4 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6634            4 :             assert_eq!(branchpoints.len(), 1);
    6635            4 :             assert_eq!(
    6636            4 :                 branchpoints[0],
    6637            4 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6638            4 :             );
    6639            4 :         }
    6640            4 : 
    6641            4 :         // You can read the key from the child branch even though the parent is
    6642            4 :         // Broken, as long as you don't need to access data from the parent.
    6643            4 :         assert_eq!(
    6644            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6645            4 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6646            4 :         );
    6647            4 : 
    6648            4 :         // This needs to traverse to the parent, and fails.
    6649            4 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6650            4 :         assert!(
    6651            4 :             err.to_string().starts_with(&format!(
    6652            4 :                 "bad state on timeline {}: Broken",
    6653            4 :                 tline.timeline_id
    6654            4 :             )),
    6655            4 :             "{err}"
    6656            4 :         );
    6657            4 : 
    6658            4 :         Ok(())
    6659            4 :     }
    6660              : 
    6661              :     #[tokio::test]
    6662            4 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6663            4 :         let (tenant, ctx) =
    6664            4 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6665            4 :                 .await?
    6666            4 :                 .load()
    6667            4 :                 .await;
    6668            4 :         let tline = tenant
    6669            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6670            4 :             .await?;
    6671            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6672            4 : 
    6673            4 :         tenant
    6674            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6675            4 :             .await?;
    6676            4 :         let newtline = tenant
    6677            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6678            4 :             .expect("Should have a local timeline");
    6679            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6680            4 :         tenant
    6681            4 :             .gc_iteration(
    6682            4 :                 Some(TIMELINE_ID),
    6683            4 :                 0x10,
    6684            4 :                 Duration::ZERO,
    6685            4 :                 &CancellationToken::new(),
    6686            4 :                 &ctx,
    6687            4 :             )
    6688            4 :             .await?;
    6689            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6690            4 : 
    6691            4 :         Ok(())
    6692            4 :     }
    6693              :     #[tokio::test]
    6694            4 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6695            4 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6696            4 :             .await?
    6697            4 :             .load()
    6698            4 :             .await;
    6699            4 :         let tline = tenant
    6700            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6701            4 :             .await?;
    6702            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6703            4 : 
    6704            4 :         tenant
    6705            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6706            4 :             .await?;
    6707            4 :         let newtline = tenant
    6708            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6709            4 :             .expect("Should have a local timeline");
    6710            4 : 
    6711            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6712            4 : 
    6713            4 :         // run gc on parent
    6714            4 :         tenant
    6715            4 :             .gc_iteration(
    6716            4 :                 Some(TIMELINE_ID),
    6717            4 :                 0x10,
    6718            4 :                 Duration::ZERO,
    6719            4 :                 &CancellationToken::new(),
    6720            4 :                 &ctx,
    6721            4 :             )
    6722            4 :             .await?;
    6723            4 : 
    6724            4 :         // Check that the data is still accessible on the branch.
    6725            4 :         assert_eq!(
    6726            4 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6727            4 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6728            4 :         );
    6729            4 : 
    6730            4 :         Ok(())
    6731            4 :     }
    6732              : 
    6733              :     #[tokio::test]
    6734            4 :     async fn timeline_load() -> anyhow::Result<()> {
    6735            4 :         const TEST_NAME: &str = "timeline_load";
    6736            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6737            4 :         {
    6738            4 :             let (tenant, ctx) = harness.load().await;
    6739            4 :             let tline = tenant
    6740            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6741            4 :                 .await?;
    6742            4 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6743            4 :             // so that all uploads finish & we can call harness.load() below again
    6744            4 :             tenant
    6745            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6746            4 :                 .instrument(harness.span())
    6747            4 :                 .await
    6748            4 :                 .ok()
    6749            4 :                 .unwrap();
    6750            4 :         }
    6751            4 : 
    6752            4 :         let (tenant, _ctx) = harness.load().await;
    6753            4 :         tenant
    6754            4 :             .get_timeline(TIMELINE_ID, true)
    6755            4 :             .expect("cannot load timeline");
    6756            4 : 
    6757            4 :         Ok(())
    6758            4 :     }
    6759              : 
    6760              :     #[tokio::test]
    6761            4 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6762            4 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6763            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6764            4 :         // create two timelines
    6765            4 :         {
    6766            4 :             let (tenant, ctx) = harness.load().await;
    6767            4 :             let tline = tenant
    6768            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6769            4 :                 .await?;
    6770            4 : 
    6771            4 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6772            4 : 
    6773            4 :             let child_tline = tenant
    6774            4 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6775            4 :                 .await?;
    6776            4 :             child_tline.set_state(TimelineState::Active);
    6777            4 : 
    6778            4 :             let newtline = tenant
    6779            4 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6780            4 :                 .expect("Should have a local timeline");
    6781            4 : 
    6782            4 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6783            4 : 
    6784            4 :             // so that all uploads finish & we can call harness.load() below again
    6785            4 :             tenant
    6786            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6787            4 :                 .instrument(harness.span())
    6788            4 :                 .await
    6789            4 :                 .ok()
    6790            4 :                 .unwrap();
    6791            4 :         }
    6792            4 : 
    6793            4 :         // check that both of them are initially unloaded
    6794            4 :         let (tenant, _ctx) = harness.load().await;
    6795            4 : 
    6796            4 :         // check that both, child and ancestor are loaded
    6797            4 :         let _child_tline = tenant
    6798            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6799            4 :             .expect("cannot get child timeline loaded");
    6800            4 : 
    6801            4 :         let _ancestor_tline = tenant
    6802            4 :             .get_timeline(TIMELINE_ID, true)
    6803            4 :             .expect("cannot get ancestor timeline loaded");
    6804            4 : 
    6805            4 :         Ok(())
    6806            4 :     }
    6807              : 
    6808              :     #[tokio::test]
    6809            4 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6810            4 :         use storage_layer::AsLayerDesc;
    6811            4 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6812            4 :             .await?
    6813            4 :             .load()
    6814            4 :             .await;
    6815            4 :         let tline = tenant
    6816            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6817            4 :             .await?;
    6818            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6819            4 : 
    6820            4 :         let layer_map = tline.layers.read().await;
    6821            4 :         let level0_deltas = layer_map
    6822            4 :             .layer_map()?
    6823            4 :             .level0_deltas()
    6824            4 :             .iter()
    6825            8 :             .map(|desc| layer_map.get_from_desc(desc))
    6826            4 :             .collect::<Vec<_>>();
    6827            4 : 
    6828            4 :         assert!(!level0_deltas.is_empty());
    6829            4 : 
    6830           12 :         for delta in level0_deltas {
    6831            4 :             // Ensure we are dumping a delta layer here
    6832            8 :             assert!(delta.layer_desc().is_delta);
    6833            8 :             delta.dump(true, &ctx).await.unwrap();
    6834            4 :         }
    6835            4 : 
    6836            4 :         Ok(())
    6837            4 :     }
    6838              : 
    6839              :     #[tokio::test]
    6840            4 :     async fn test_images() -> anyhow::Result<()> {
    6841            4 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6842            4 :         let tline = tenant
    6843            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6844            4 :             .await?;
    6845            4 : 
    6846            4 :         let mut writer = tline.writer().await;
    6847            4 :         writer
    6848            4 :             .put(
    6849            4 :                 *TEST_KEY,
    6850            4 :                 Lsn(0x10),
    6851            4 :                 &Value::Image(test_img("foo at 0x10")),
    6852            4 :                 &ctx,
    6853            4 :             )
    6854            4 :             .await?;
    6855            4 :         writer.finish_write(Lsn(0x10));
    6856            4 :         drop(writer);
    6857            4 : 
    6858            4 :         tline.freeze_and_flush().await?;
    6859            4 :         tline
    6860            4 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6861            4 :             .await?;
    6862            4 : 
    6863            4 :         let mut writer = tline.writer().await;
    6864            4 :         writer
    6865            4 :             .put(
    6866            4 :                 *TEST_KEY,
    6867            4 :                 Lsn(0x20),
    6868            4 :                 &Value::Image(test_img("foo at 0x20")),
    6869            4 :                 &ctx,
    6870            4 :             )
    6871            4 :             .await?;
    6872            4 :         writer.finish_write(Lsn(0x20));
    6873            4 :         drop(writer);
    6874            4 : 
    6875            4 :         tline.freeze_and_flush().await?;
    6876            4 :         tline
    6877            4 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6878            4 :             .await?;
    6879            4 : 
    6880            4 :         let mut writer = tline.writer().await;
    6881            4 :         writer
    6882            4 :             .put(
    6883            4 :                 *TEST_KEY,
    6884            4 :                 Lsn(0x30),
    6885            4 :                 &Value::Image(test_img("foo at 0x30")),
    6886            4 :                 &ctx,
    6887            4 :             )
    6888            4 :             .await?;
    6889            4 :         writer.finish_write(Lsn(0x30));
    6890            4 :         drop(writer);
    6891            4 : 
    6892            4 :         tline.freeze_and_flush().await?;
    6893            4 :         tline
    6894            4 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6895            4 :             .await?;
    6896            4 : 
    6897            4 :         let mut writer = tline.writer().await;
    6898            4 :         writer
    6899            4 :             .put(
    6900            4 :                 *TEST_KEY,
    6901            4 :                 Lsn(0x40),
    6902            4 :                 &Value::Image(test_img("foo at 0x40")),
    6903            4 :                 &ctx,
    6904            4 :             )
    6905            4 :             .await?;
    6906            4 :         writer.finish_write(Lsn(0x40));
    6907            4 :         drop(writer);
    6908            4 : 
    6909            4 :         tline.freeze_and_flush().await?;
    6910            4 :         tline
    6911            4 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6912            4 :             .await?;
    6913            4 : 
    6914            4 :         assert_eq!(
    6915            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6916            4 :             test_img("foo at 0x10")
    6917            4 :         );
    6918            4 :         assert_eq!(
    6919            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6920            4 :             test_img("foo at 0x10")
    6921            4 :         );
    6922            4 :         assert_eq!(
    6923            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6924            4 :             test_img("foo at 0x20")
    6925            4 :         );
    6926            4 :         assert_eq!(
    6927            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6928            4 :             test_img("foo at 0x30")
    6929            4 :         );
    6930            4 :         assert_eq!(
    6931            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6932            4 :             test_img("foo at 0x40")
    6933            4 :         );
    6934            4 : 
    6935            4 :         Ok(())
    6936            4 :     }
    6937              : 
    6938            8 :     async fn bulk_insert_compact_gc(
    6939            8 :         tenant: &Tenant,
    6940            8 :         timeline: &Arc<Timeline>,
    6941            8 :         ctx: &RequestContext,
    6942            8 :         lsn: Lsn,
    6943            8 :         repeat: usize,
    6944            8 :         key_count: usize,
    6945            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6946            8 :         let compact = true;
    6947            8 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6948            8 :     }
    6949              : 
    6950           16 :     async fn bulk_insert_maybe_compact_gc(
    6951           16 :         tenant: &Tenant,
    6952           16 :         timeline: &Arc<Timeline>,
    6953           16 :         ctx: &RequestContext,
    6954           16 :         mut lsn: Lsn,
    6955           16 :         repeat: usize,
    6956           16 :         key_count: usize,
    6957           16 :         compact: bool,
    6958           16 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6959           16 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6960           16 : 
    6961           16 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6962           16 :         let mut blknum = 0;
    6963           16 : 
    6964           16 :         // Enforce that key range is monotonously increasing
    6965           16 :         let mut keyspace = KeySpaceAccum::new();
    6966           16 : 
    6967           16 :         let cancel = CancellationToken::new();
    6968           16 : 
    6969           16 :         for _ in 0..repeat {
    6970          800 :             for _ in 0..key_count {
    6971      8000000 :                 test_key.field6 = blknum;
    6972      8000000 :                 let mut writer = timeline.writer().await;
    6973      8000000 :                 writer
    6974      8000000 :                     .put(
    6975      8000000 :                         test_key,
    6976      8000000 :                         lsn,
    6977      8000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6978      8000000 :                         ctx,
    6979      8000000 :                     )
    6980      8000000 :                     .await?;
    6981      8000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6982      8000000 :                 writer.finish_write(lsn);
    6983      8000000 :                 drop(writer);
    6984      8000000 : 
    6985      8000000 :                 keyspace.add_key(test_key);
    6986      8000000 : 
    6987      8000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6988      8000000 :                 blknum += 1;
    6989              :             }
    6990              : 
    6991          800 :             timeline.freeze_and_flush().await?;
    6992          800 :             if compact {
    6993              :                 // this requires timeline to be &Arc<Timeline>
    6994          400 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    6995          400 :             }
    6996              : 
    6997              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6998              :             // originally was.
    6999          800 :             let res = tenant
    7000          800 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7001          800 :                 .await?;
    7002              : 
    7003          800 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7004              :         }
    7005              : 
    7006           16 :         Ok(inserted)
    7007           16 :     }
    7008              : 
    7009              :     //
    7010              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7011              :     // Repeat 50 times.
    7012              :     //
    7013              :     #[tokio::test]
    7014            4 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7015            4 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7016            4 :         let (tenant, ctx) = harness.load().await;
    7017            4 :         let tline = tenant
    7018            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7019            4 :             .await?;
    7020            4 : 
    7021            4 :         let lsn = Lsn(0x10);
    7022            4 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7023            4 : 
    7024            4 :         Ok(())
    7025            4 :     }
    7026              : 
    7027              :     // Test the vectored get real implementation against a simple sequential implementation.
    7028              :     //
    7029              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    7030              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    7031              :     // grow to the right on the X axis.
    7032              :     //                       [Delta]
    7033              :     //                 [Delta]
    7034              :     //           [Delta]
    7035              :     //    [Delta]
    7036              :     // ------------ Image ---------------
    7037              :     //
    7038              :     // After layer generation we pick the ranges to query as follows:
    7039              :     // 1. The beginning of each delta layer
    7040              :     // 2. At the seam between two adjacent delta layers
    7041              :     //
    7042              :     // There's one major downside to this test: delta layers only contains images,
    7043              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    7044              :     #[tokio::test]
    7045            4 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7046            4 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7047            4 :         let (tenant, ctx) = harness.load().await;
    7048            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7049            4 :         let tline = tenant
    7050            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7051            4 :             .await?;
    7052            4 : 
    7053            4 :         let lsn = Lsn(0x10);
    7054            4 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7055            4 : 
    7056            4 :         let guard = tline.layers.read().await;
    7057            4 :         let lm = guard.layer_map()?;
    7058            4 : 
    7059            4 :         lm.dump(true, &ctx).await?;
    7060            4 : 
    7061            4 :         let mut reads = Vec::new();
    7062            4 :         let mut prev = None;
    7063           24 :         lm.iter_historic_layers().for_each(|desc| {
    7064           24 :             if !desc.is_delta() {
    7065            4 :                 prev = Some(desc.clone());
    7066            4 :                 return;
    7067           20 :             }
    7068           20 : 
    7069           20 :             let start = desc.key_range.start;
    7070           20 :             let end = desc
    7071           20 :                 .key_range
    7072           20 :                 .start
    7073           20 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    7074           20 :             reads.push(KeySpace {
    7075           20 :                 ranges: vec![start..end],
    7076           20 :             });
    7077            4 : 
    7078           20 :             if let Some(prev) = &prev {
    7079           20 :                 if !prev.is_delta() {
    7080           20 :                     return;
    7081            4 :                 }
    7082            0 : 
    7083            0 :                 let first_range = Key {
    7084            0 :                     field6: prev.key_range.end.field6 - 4,
    7085            0 :                     ..prev.key_range.end
    7086            0 :                 }..prev.key_range.end;
    7087            0 : 
    7088            0 :                 let second_range = desc.key_range.start..Key {
    7089            0 :                     field6: desc.key_range.start.field6 + 4,
    7090            0 :                     ..desc.key_range.start
    7091            0 :                 };
    7092            0 : 
    7093            0 :                 reads.push(KeySpace {
    7094            0 :                     ranges: vec![first_range, second_range],
    7095            0 :                 });
    7096            4 :             };
    7097            4 : 
    7098            4 :             prev = Some(desc.clone());
    7099           24 :         });
    7100            4 : 
    7101            4 :         drop(guard);
    7102            4 : 
    7103            4 :         // Pick a big LSN such that we query over all the changes.
    7104            4 :         let reads_lsn = Lsn(u64::MAX - 1);
    7105            4 : 
    7106           24 :         for read in reads {
    7107           20 :             info!("Doing vectored read on {:?}", read);
    7108            4 : 
    7109           20 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7110            4 : 
    7111           20 :             let vectored_res = tline
    7112           20 :                 .get_vectored_impl(
    7113           20 :                     query,
    7114           20 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7115           20 :                     &ctx,
    7116           20 :                 )
    7117           20 :                 .await;
    7118            4 : 
    7119           20 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7120           20 :             let mut expect_missing = false;
    7121           20 :             let mut key = read.start().unwrap();
    7122          660 :             while key != read.end().unwrap() {
    7123          640 :                 if let Some(lsns) = inserted.get(&key) {
    7124          640 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7125          640 :                     match expected_lsn {
    7126          640 :                         Some(lsn) => {
    7127          640 :                             expected_lsns.insert(key, *lsn);
    7128          640 :                         }
    7129            4 :                         None => {
    7130            4 :                             expect_missing = true;
    7131            0 :                             break;
    7132            4 :                         }
    7133            4 :                     }
    7134            4 :                 } else {
    7135            4 :                     expect_missing = true;
    7136            0 :                     break;
    7137            4 :                 }
    7138            4 : 
    7139          640 :                 key = key.next();
    7140            4 :             }
    7141            4 : 
    7142           20 :             if expect_missing {
    7143            4 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7144            4 :             } else {
    7145          640 :                 for (key, image) in vectored_res? {
    7146          640 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7147          640 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7148          640 :                     assert_eq!(image?, expected_image);
    7149            4 :                 }
    7150            4 :             }
    7151            4 :         }
    7152            4 : 
    7153            4 :         Ok(())
    7154            4 :     }
    7155              : 
    7156              :     #[tokio::test]
    7157            4 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7158            4 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7159            4 : 
    7160            4 :         let (tenant, ctx) = harness.load().await;
    7161            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7162            4 :         let (tline, ctx) = tenant
    7163            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7164            4 :             .await?;
    7165            4 :         let tline = tline.raw_timeline().unwrap();
    7166            4 : 
    7167            4 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7168            4 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7169            4 :         modification.set_lsn(Lsn(0x1008))?;
    7170            4 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7171            4 :         modification.commit(&ctx).await?;
    7172            4 : 
    7173            4 :         let child_timeline_id = TimelineId::generate();
    7174            4 :         tenant
    7175            4 :             .branch_timeline_test(
    7176            4 :                 tline,
    7177            4 :                 child_timeline_id,
    7178            4 :                 Some(tline.get_last_record_lsn()),
    7179            4 :                 &ctx,
    7180            4 :             )
    7181            4 :             .await?;
    7182            4 : 
    7183            4 :         let child_timeline = tenant
    7184            4 :             .get_timeline(child_timeline_id, true)
    7185            4 :             .expect("Should have the branched timeline");
    7186            4 : 
    7187            4 :         let aux_keyspace = KeySpace {
    7188            4 :             ranges: vec![NON_INHERITED_RANGE],
    7189            4 :         };
    7190            4 :         let read_lsn = child_timeline.get_last_record_lsn();
    7191            4 : 
    7192            4 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7193            4 : 
    7194            4 :         let vectored_res = child_timeline
    7195            4 :             .get_vectored_impl(
    7196            4 :                 query,
    7197            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7198            4 :                 &ctx,
    7199            4 :             )
    7200            4 :             .await;
    7201            4 : 
    7202            4 :         let images = vectored_res?;
    7203            4 :         assert!(images.is_empty());
    7204            4 :         Ok(())
    7205            4 :     }
    7206              : 
    7207              :     // Test that vectored get handles layer gaps correctly
    7208              :     // by advancing into the next ancestor timeline if required.
    7209              :     //
    7210              :     // The test generates timelines that look like the diagram below.
    7211              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    7212              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    7213              :     //
    7214              :     // ```
    7215              :     //-------------------------------+
    7216              :     //                          ...  |
    7217              :     //               [   L1   ]      |
    7218              :     //     [ / L1   ]                | Child Timeline
    7219              :     // ...                           |
    7220              :     // ------------------------------+
    7221              :     //     [ X L1   ]                | Parent Timeline
    7222              :     // ------------------------------+
    7223              :     // ```
    7224              :     #[tokio::test]
    7225            4 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7226            4 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7227            4 :             // Make compaction deterministic
    7228            4 :             gc_period: Some(Duration::ZERO),
    7229            4 :             compaction_period: Some(Duration::ZERO),
    7230            4 :             // Encourage creation of L1 layers
    7231            4 :             checkpoint_distance: Some(16 * 1024),
    7232            4 :             compaction_target_size: Some(8 * 1024),
    7233            4 :             ..Default::default()
    7234            4 :         };
    7235            4 : 
    7236            4 :         let harness = TenantHarness::create_custom(
    7237            4 :             "test_get_vectored_key_gap",
    7238            4 :             tenant_conf,
    7239            4 :             TenantId::generate(),
    7240            4 :             ShardIdentity::unsharded(),
    7241            4 :             Generation::new(0xdeadbeef),
    7242            4 :         )
    7243            4 :         .await?;
    7244            4 :         let (tenant, ctx) = harness.load().await;
    7245            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7246            4 : 
    7247            4 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7248            4 :         let gap_at_key = current_key.add(100);
    7249            4 :         let mut current_lsn = Lsn(0x10);
    7250            4 : 
    7251            4 :         const KEY_COUNT: usize = 10_000;
    7252            4 : 
    7253            4 :         let timeline_id = TimelineId::generate();
    7254            4 :         let current_timeline = tenant
    7255            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7256            4 :             .await?;
    7257            4 : 
    7258            4 :         current_lsn += 0x100;
    7259            4 : 
    7260            4 :         let mut writer = current_timeline.writer().await;
    7261            4 :         writer
    7262            4 :             .put(
    7263            4 :                 gap_at_key,
    7264            4 :                 current_lsn,
    7265            4 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    7266            4 :                 &ctx,
    7267            4 :             )
    7268            4 :             .await?;
    7269            4 :         writer.finish_write(current_lsn);
    7270            4 :         drop(writer);
    7271            4 : 
    7272            4 :         let mut latest_lsns = HashMap::new();
    7273            4 :         latest_lsns.insert(gap_at_key, current_lsn);
    7274            4 : 
    7275            4 :         current_timeline.freeze_and_flush().await?;
    7276            4 : 
    7277            4 :         let child_timeline_id = TimelineId::generate();
    7278            4 : 
    7279            4 :         tenant
    7280            4 :             .branch_timeline_test(
    7281            4 :                 &current_timeline,
    7282            4 :                 child_timeline_id,
    7283            4 :                 Some(current_lsn),
    7284            4 :                 &ctx,
    7285            4 :             )
    7286            4 :             .await?;
    7287            4 :         let child_timeline = tenant
    7288            4 :             .get_timeline(child_timeline_id, true)
    7289            4 :             .expect("Should have the branched timeline");
    7290            4 : 
    7291        40004 :         for i in 0..KEY_COUNT {
    7292        40000 :             if current_key == gap_at_key {
    7293            4 :                 current_key = current_key.next();
    7294            4 :                 continue;
    7295        39996 :             }
    7296        39996 : 
    7297        39996 :             current_lsn += 0x10;
    7298            4 : 
    7299        39996 :             let mut writer = child_timeline.writer().await;
    7300        39996 :             writer
    7301        39996 :                 .put(
    7302        39996 :                     current_key,
    7303        39996 :                     current_lsn,
    7304        39996 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    7305        39996 :                     &ctx,
    7306        39996 :                 )
    7307        39996 :                 .await?;
    7308        39996 :             writer.finish_write(current_lsn);
    7309        39996 :             drop(writer);
    7310        39996 : 
    7311        39996 :             latest_lsns.insert(current_key, current_lsn);
    7312        39996 :             current_key = current_key.next();
    7313        39996 : 
    7314        39996 :             // Flush every now and then to encourage layer file creation.
    7315        39996 :             if i % 500 == 0 {
    7316           80 :                 child_timeline.freeze_and_flush().await?;
    7317        39916 :             }
    7318            4 :         }
    7319            4 : 
    7320            4 :         child_timeline.freeze_and_flush().await?;
    7321            4 :         let mut flags = EnumSet::new();
    7322            4 :         flags.insert(CompactFlags::ForceRepartition);
    7323            4 :         child_timeline
    7324            4 :             .compact(&CancellationToken::new(), flags, &ctx)
    7325            4 :             .await?;
    7326            4 : 
    7327            4 :         let key_near_end = {
    7328            4 :             let mut tmp = current_key;
    7329            4 :             tmp.field6 -= 10;
    7330            4 :             tmp
    7331            4 :         };
    7332            4 : 
    7333            4 :         let key_near_gap = {
    7334            4 :             let mut tmp = gap_at_key;
    7335            4 :             tmp.field6 -= 10;
    7336            4 :             tmp
    7337            4 :         };
    7338            4 : 
    7339            4 :         let read = KeySpace {
    7340            4 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7341            4 :         };
    7342            4 : 
    7343            4 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7344            4 : 
    7345            4 :         let results = child_timeline
    7346            4 :             .get_vectored_impl(
    7347            4 :                 query,
    7348            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7349            4 :                 &ctx,
    7350            4 :             )
    7351            4 :             .await?;
    7352            4 : 
    7353           88 :         for (key, img_res) in results {
    7354           84 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7355           84 :             assert_eq!(img_res?, expected);
    7356            4 :         }
    7357            4 : 
    7358            4 :         Ok(())
    7359            4 :     }
    7360              : 
    7361              :     // Test that vectored get descends into ancestor timelines correctly and
    7362              :     // does not return an image that's newer than requested.
    7363              :     //
    7364              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7365              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7366              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7367              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7368              :     // order to avoid returning an image that's too new. The test below constructs such
    7369              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7370              :     // ```
    7371              :     //    LSN
    7372              :     //     ^
    7373              :     //     |
    7374              :     //     |
    7375              :     // 500 | --------------------------------------> branch point
    7376              :     // 400 |        X
    7377              :     // 300 |        X
    7378              :     // 200 | --------------------------------------> requested lsn
    7379              :     // 100 |        X
    7380              :     //     |---------------------------------------> Key
    7381              :     //              |
    7382              :     //              ------> requested key
    7383              :     //
    7384              :     // Legend:
    7385              :     // * X - page images
    7386              :     // ```
    7387              :     #[tokio::test]
    7388            4 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7389            4 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7390            4 :         let (tenant, ctx) = harness.load().await;
    7391            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7392            4 : 
    7393            4 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7394            4 :         let end_key = start_key.add(1000);
    7395            4 :         let child_gap_at_key = start_key.add(500);
    7396            4 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7397            4 : 
    7398            4 :         let mut current_lsn = Lsn(0x10);
    7399            4 : 
    7400            4 :         let timeline_id = TimelineId::generate();
    7401            4 :         let parent_timeline = tenant
    7402            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7403            4 :             .await?;
    7404            4 : 
    7405            4 :         current_lsn += 0x100;
    7406            4 : 
    7407           16 :         for _ in 0..3 {
    7408           12 :             let mut key = start_key;
    7409        12012 :             while key < end_key {
    7410        12000 :                 current_lsn += 0x10;
    7411        12000 : 
    7412        12000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    7413            4 : 
    7414        12000 :                 let mut writer = parent_timeline.writer().await;
    7415        12000 :                 writer
    7416        12000 :                     .put(
    7417        12000 :                         key,
    7418        12000 :                         current_lsn,
    7419        12000 :                         &Value::Image(test_img(&image_value)),
    7420        12000 :                         &ctx,
    7421        12000 :                     )
    7422        12000 :                     .await?;
    7423        12000 :                 writer.finish_write(current_lsn);
    7424        12000 : 
    7425        12000 :                 if key == child_gap_at_key {
    7426           12 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7427        11988 :                 }
    7428            4 : 
    7429        12000 :                 key = key.next();
    7430            4 :             }
    7431            4 : 
    7432           12 :             parent_timeline.freeze_and_flush().await?;
    7433            4 :         }
    7434            4 : 
    7435            4 :         let child_timeline_id = TimelineId::generate();
    7436            4 : 
    7437            4 :         let child_timeline = tenant
    7438            4 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7439            4 :             .await?;
    7440            4 : 
    7441            4 :         let mut key = start_key;
    7442         4004 :         while key < end_key {
    7443         4000 :             if key == child_gap_at_key {
    7444            4 :                 key = key.next();
    7445            4 :                 continue;
    7446         3996 :             }
    7447         3996 : 
    7448         3996 :             current_lsn += 0x10;
    7449            4 : 
    7450         3996 :             let mut writer = child_timeline.writer().await;
    7451         3996 :             writer
    7452         3996 :                 .put(
    7453         3996 :                     key,
    7454         3996 :                     current_lsn,
    7455         3996 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    7456         3996 :                     &ctx,
    7457         3996 :                 )
    7458         3996 :                 .await?;
    7459         3996 :             writer.finish_write(current_lsn);
    7460         3996 : 
    7461         3996 :             key = key.next();
    7462            4 :         }
    7463            4 : 
    7464            4 :         child_timeline.freeze_and_flush().await?;
    7465            4 : 
    7466            4 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7467            4 :         let mut query_lsns = Vec::new();
    7468           12 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7469           72 :             for offset in lsn_offsets {
    7470           60 :                 query_lsns.push(Lsn(image_lsn
    7471           60 :                     .0
    7472           60 :                     .checked_add_signed(offset)
    7473           60 :                     .expect("Shouldn't overflow")));
    7474           60 :             }
    7475            4 :         }
    7476            4 : 
    7477           64 :         for query_lsn in query_lsns {
    7478           60 :             let query = VersionedKeySpaceQuery::uniform(
    7479           60 :                 KeySpace {
    7480           60 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7481           60 :                 },
    7482           60 :                 query_lsn,
    7483           60 :             );
    7484            4 : 
    7485           60 :             let results = child_timeline
    7486           60 :                 .get_vectored_impl(
    7487           60 :                     query,
    7488           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7489           60 :                     &ctx,
    7490           60 :                 )
    7491           60 :                 .await;
    7492            4 : 
    7493           60 :             let expected_item = parent_gap_lsns
    7494           60 :                 .iter()
    7495           60 :                 .rev()
    7496          136 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7497           60 : 
    7498           60 :             info!(
    7499            4 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7500            4 :                 query_lsn, expected_item
    7501            4 :             );
    7502            4 : 
    7503           60 :             match expected_item {
    7504           52 :                 Some((_, img_value)) => {
    7505           52 :                     let key_results = results.expect("No vectored get error expected");
    7506           52 :                     let key_result = &key_results[&child_gap_at_key];
    7507           52 :                     let returned_img = key_result
    7508           52 :                         .as_ref()
    7509           52 :                         .expect("No page reconstruct error expected");
    7510           52 : 
    7511           52 :                     info!(
    7512            4 :                         "Vectored read at LSN {} returned image {}",
    7513            0 :                         query_lsn,
    7514            0 :                         std::str::from_utf8(returned_img)?
    7515            4 :                     );
    7516           52 :                     assert_eq!(*returned_img, test_img(img_value));
    7517            4 :                 }
    7518            4 :                 None => {
    7519            8 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7520            4 :                 }
    7521            4 :             }
    7522            4 :         }
    7523            4 : 
    7524            4 :         Ok(())
    7525            4 :     }
    7526              : 
    7527              :     #[tokio::test]
    7528            4 :     async fn test_random_updates() -> anyhow::Result<()> {
    7529            4 :         let names_algorithms = [
    7530            4 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7531            4 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7532            4 :         ];
    7533           12 :         for (name, algorithm) in names_algorithms {
    7534            8 :             test_random_updates_algorithm(name, algorithm).await?;
    7535            4 :         }
    7536            4 :         Ok(())
    7537            4 :     }
    7538              : 
    7539            8 :     async fn test_random_updates_algorithm(
    7540            8 :         name: &'static str,
    7541            8 :         compaction_algorithm: CompactionAlgorithm,
    7542            8 :     ) -> anyhow::Result<()> {
    7543            8 :         let mut harness = TenantHarness::create(name).await?;
    7544            8 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7545            8 :             kind: compaction_algorithm,
    7546            8 :         });
    7547            8 :         let (tenant, ctx) = harness.load().await;
    7548            8 :         let tline = tenant
    7549            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7550            8 :             .await?;
    7551              : 
    7552              :         const NUM_KEYS: usize = 1000;
    7553            8 :         let cancel = CancellationToken::new();
    7554            8 : 
    7555            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7556            8 :         let mut test_key_end = test_key;
    7557            8 :         test_key_end.field6 = NUM_KEYS as u32;
    7558            8 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7559            8 : 
    7560            8 :         let mut keyspace = KeySpaceAccum::new();
    7561            8 : 
    7562            8 :         // Track when each page was last modified. Used to assert that
    7563            8 :         // a read sees the latest page version.
    7564            8 :         let mut updated = [Lsn(0); NUM_KEYS];
    7565            8 : 
    7566            8 :         let mut lsn = Lsn(0x10);
    7567              :         #[allow(clippy::needless_range_loop)]
    7568         8008 :         for blknum in 0..NUM_KEYS {
    7569         8000 :             lsn = Lsn(lsn.0 + 0x10);
    7570         8000 :             test_key.field6 = blknum as u32;
    7571         8000 :             let mut writer = tline.writer().await;
    7572         8000 :             writer
    7573         8000 :                 .put(
    7574         8000 :                     test_key,
    7575         8000 :                     lsn,
    7576         8000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7577         8000 :                     &ctx,
    7578         8000 :                 )
    7579         8000 :                 .await?;
    7580         8000 :             writer.finish_write(lsn);
    7581         8000 :             updated[blknum] = lsn;
    7582         8000 :             drop(writer);
    7583         8000 : 
    7584         8000 :             keyspace.add_key(test_key);
    7585              :         }
    7586              : 
    7587          408 :         for _ in 0..50 {
    7588       400400 :             for _ in 0..NUM_KEYS {
    7589       400000 :                 lsn = Lsn(lsn.0 + 0x10);
    7590       400000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7591       400000 :                 test_key.field6 = blknum as u32;
    7592       400000 :                 let mut writer = tline.writer().await;
    7593       400000 :                 writer
    7594       400000 :                     .put(
    7595       400000 :                         test_key,
    7596       400000 :                         lsn,
    7597       400000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7598       400000 :                         &ctx,
    7599       400000 :                     )
    7600       400000 :                     .await?;
    7601       400000 :                 writer.finish_write(lsn);
    7602       400000 :                 drop(writer);
    7603       400000 :                 updated[blknum] = lsn;
    7604              :             }
    7605              : 
    7606              :             // Read all the blocks
    7607       400000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7608       400000 :                 test_key.field6 = blknum as u32;
    7609       400000 :                 assert_eq!(
    7610       400000 :                     tline.get(test_key, lsn, &ctx).await?,
    7611       400000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7612              :                 );
    7613              :             }
    7614              : 
    7615              :             // Perform a cycle of flush, and GC
    7616          400 :             tline.freeze_and_flush().await?;
    7617          400 :             tenant
    7618          400 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7619          400 :                 .await?;
    7620              :         }
    7621              : 
    7622            8 :         Ok(())
    7623            8 :     }
    7624              : 
    7625              :     #[tokio::test]
    7626            4 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7627            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7628            4 :             .await?
    7629            4 :             .load()
    7630            4 :             .await;
    7631            4 :         let mut tline = tenant
    7632            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7633            4 :             .await?;
    7634            4 : 
    7635            4 :         const NUM_KEYS: usize = 1000;
    7636            4 : 
    7637            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7638            4 : 
    7639            4 :         let mut keyspace = KeySpaceAccum::new();
    7640            4 : 
    7641            4 :         let cancel = CancellationToken::new();
    7642            4 : 
    7643            4 :         // Track when each page was last modified. Used to assert that
    7644            4 :         // a read sees the latest page version.
    7645            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7646            4 : 
    7647            4 :         let mut lsn = Lsn(0x10);
    7648            4 :         #[allow(clippy::needless_range_loop)]
    7649         4004 :         for blknum in 0..NUM_KEYS {
    7650         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7651         4000 :             test_key.field6 = blknum as u32;
    7652         4000 :             let mut writer = tline.writer().await;
    7653         4000 :             writer
    7654         4000 :                 .put(
    7655         4000 :                     test_key,
    7656         4000 :                     lsn,
    7657         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7658         4000 :                     &ctx,
    7659         4000 :                 )
    7660         4000 :                 .await?;
    7661         4000 :             writer.finish_write(lsn);
    7662         4000 :             updated[blknum] = lsn;
    7663         4000 :             drop(writer);
    7664         4000 : 
    7665         4000 :             keyspace.add_key(test_key);
    7666            4 :         }
    7667            4 : 
    7668          204 :         for _ in 0..50 {
    7669          200 :             let new_tline_id = TimelineId::generate();
    7670          200 :             tenant
    7671          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7672          200 :                 .await?;
    7673          200 :             tline = tenant
    7674          200 :                 .get_timeline(new_tline_id, true)
    7675          200 :                 .expect("Should have the branched timeline");
    7676            4 : 
    7677       200200 :             for _ in 0..NUM_KEYS {
    7678       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7679       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7680       200000 :                 test_key.field6 = blknum as u32;
    7681       200000 :                 let mut writer = tline.writer().await;
    7682       200000 :                 writer
    7683       200000 :                     .put(
    7684       200000 :                         test_key,
    7685       200000 :                         lsn,
    7686       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7687       200000 :                         &ctx,
    7688       200000 :                     )
    7689       200000 :                     .await?;
    7690       200000 :                 println!("updating {} at {}", blknum, lsn);
    7691       200000 :                 writer.finish_write(lsn);
    7692       200000 :                 drop(writer);
    7693       200000 :                 updated[blknum] = lsn;
    7694            4 :             }
    7695            4 : 
    7696            4 :             // Read all the blocks
    7697       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7698       200000 :                 test_key.field6 = blknum as u32;
    7699       200000 :                 assert_eq!(
    7700       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7701       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7702            4 :                 );
    7703            4 :             }
    7704            4 : 
    7705            4 :             // Perform a cycle of flush, compact, and GC
    7706          200 :             tline.freeze_and_flush().await?;
    7707          200 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7708          200 :             tenant
    7709          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7710          200 :                 .await?;
    7711            4 :         }
    7712            4 : 
    7713            4 :         Ok(())
    7714            4 :     }
    7715              : 
    7716              :     #[tokio::test]
    7717            4 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7718            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7719            4 :             .await?
    7720            4 :             .load()
    7721            4 :             .await;
    7722            4 :         let mut tline = tenant
    7723            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7724            4 :             .await?;
    7725            4 : 
    7726            4 :         const NUM_KEYS: usize = 100;
    7727            4 :         const NUM_TLINES: usize = 50;
    7728            4 : 
    7729            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7730            4 :         // Track page mutation lsns across different timelines.
    7731            4 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7732            4 : 
    7733            4 :         let mut lsn = Lsn(0x10);
    7734            4 : 
    7735            4 :         #[allow(clippy::needless_range_loop)]
    7736          204 :         for idx in 0..NUM_TLINES {
    7737          200 :             let new_tline_id = TimelineId::generate();
    7738          200 :             tenant
    7739          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7740          200 :                 .await?;
    7741          200 :             tline = tenant
    7742          200 :                 .get_timeline(new_tline_id, true)
    7743          200 :                 .expect("Should have the branched timeline");
    7744            4 : 
    7745        20200 :             for _ in 0..NUM_KEYS {
    7746        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7747        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7748        20000 :                 test_key.field6 = blknum as u32;
    7749        20000 :                 let mut writer = tline.writer().await;
    7750        20000 :                 writer
    7751        20000 :                     .put(
    7752        20000 :                         test_key,
    7753        20000 :                         lsn,
    7754        20000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7755        20000 :                         &ctx,
    7756        20000 :                     )
    7757        20000 :                     .await?;
    7758        20000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7759        20000 :                 writer.finish_write(lsn);
    7760        20000 :                 drop(writer);
    7761        20000 :                 updated[idx][blknum] = lsn;
    7762            4 :             }
    7763            4 :         }
    7764            4 : 
    7765            4 :         // Read pages from leaf timeline across all ancestors.
    7766          200 :         for (idx, lsns) in updated.iter().enumerate() {
    7767        20000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7768            4 :                 // Skip empty mutations.
    7769        20000 :                 if lsn.0 == 0 {
    7770         7367 :                     continue;
    7771        12633 :                 }
    7772        12633 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7773        12633 :                 test_key.field6 = blknum as u32;
    7774        12633 :                 assert_eq!(
    7775        12633 :                     tline.get(test_key, *lsn, &ctx).await?,
    7776        12633 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7777            4 :                 );
    7778            4 :             }
    7779            4 :         }
    7780            4 :         Ok(())
    7781            4 :     }
    7782              : 
    7783              :     #[tokio::test]
    7784            4 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7785            4 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7786            4 :             .await?
    7787            4 :             .load()
    7788            4 :             .await;
    7789            4 : 
    7790            4 :         let initdb_lsn = Lsn(0x20);
    7791            4 :         let (utline, ctx) = tenant
    7792            4 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7793            4 :             .await?;
    7794            4 :         let tline = utline.raw_timeline().unwrap();
    7795            4 : 
    7796            4 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7797            4 :         tline.maybe_spawn_flush_loop();
    7798            4 : 
    7799            4 :         // Make sure the timeline has the minimum set of required keys for operation.
    7800            4 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7801            4 :         // Except if you `put` at `initdb_lsn`.
    7802            4 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7803            4 :         // It uses `repartition()`, which assumes some keys to be present.
    7804            4 :         // Let's make sure the test timeline can handle that case.
    7805            4 :         {
    7806            4 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7807            4 :             assert_eq!(
    7808            4 :                 timeline::FlushLoopState::Running {
    7809            4 :                     expect_initdb_optimization: false,
    7810            4 :                     initdb_optimization_count: 0,
    7811            4 :                 },
    7812            4 :                 *state
    7813            4 :             );
    7814            4 :             *state = timeline::FlushLoopState::Running {
    7815            4 :                 expect_initdb_optimization: true,
    7816            4 :                 initdb_optimization_count: 0,
    7817            4 :             };
    7818            4 :         }
    7819            4 : 
    7820            4 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7821            4 :         // As explained above, the optimization requires some keys to be present.
    7822            4 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7823            4 :         // This is what `create_test_timeline` does, by the way.
    7824            4 :         let mut modification = tline.begin_modification(initdb_lsn);
    7825            4 :         modification
    7826            4 :             .init_empty_test_timeline()
    7827            4 :             .context("init_empty_test_timeline")?;
    7828            4 :         modification
    7829            4 :             .commit(&ctx)
    7830            4 :             .await
    7831            4 :             .context("commit init_empty_test_timeline modification")?;
    7832            4 : 
    7833            4 :         // Do the flush. The flush code will check the expectations that we set above.
    7834            4 :         tline.freeze_and_flush().await?;
    7835            4 : 
    7836            4 :         // assert freeze_and_flush exercised the initdb optimization
    7837            4 :         {
    7838            4 :             let state = tline.flush_loop_state.lock().unwrap();
    7839            4 :             let timeline::FlushLoopState::Running {
    7840            4 :                 expect_initdb_optimization,
    7841            4 :                 initdb_optimization_count,
    7842            4 :             } = *state
    7843            4 :             else {
    7844            4 :                 panic!("unexpected state: {:?}", *state);
    7845            4 :             };
    7846            4 :             assert!(expect_initdb_optimization);
    7847            4 :             assert!(initdb_optimization_count > 0);
    7848            4 :         }
    7849            4 :         Ok(())
    7850            4 :     }
    7851              : 
    7852              :     #[tokio::test]
    7853            4 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7854            4 :         let name = "test_create_guard_crash";
    7855            4 :         let harness = TenantHarness::create(name).await?;
    7856            4 :         {
    7857            4 :             let (tenant, ctx) = harness.load().await;
    7858            4 :             let (tline, _ctx) = tenant
    7859            4 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7860            4 :                 .await?;
    7861            4 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7862            4 :             let raw_tline = tline.raw_timeline().unwrap();
    7863            4 :             raw_tline
    7864            4 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7865            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))
    7866            4 :                 .await;
    7867            4 :             std::mem::forget(tline);
    7868            4 :         }
    7869            4 : 
    7870            4 :         let (tenant, _) = harness.load().await;
    7871            4 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7872            4 :             Ok(_) => panic!("timeline should've been removed during load"),
    7873            4 :             Err(e) => {
    7874            4 :                 assert_eq!(
    7875            4 :                     e,
    7876            4 :                     GetTimelineError::NotFound {
    7877            4 :                         tenant_id: tenant.tenant_shard_id,
    7878            4 :                         timeline_id: TIMELINE_ID,
    7879            4 :                     }
    7880            4 :                 )
    7881            4 :             }
    7882            4 :         }
    7883            4 : 
    7884            4 :         assert!(
    7885            4 :             !harness
    7886            4 :                 .conf
    7887            4 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7888            4 :                 .exists()
    7889            4 :         );
    7890            4 : 
    7891            4 :         Ok(())
    7892            4 :     }
    7893              : 
    7894              :     #[tokio::test]
    7895            4 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7896            4 :         let names_algorithms = [
    7897            4 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7898            4 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7899            4 :         ];
    7900           12 :         for (name, algorithm) in names_algorithms {
    7901            8 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7902            4 :         }
    7903            4 :         Ok(())
    7904            4 :     }
    7905              : 
    7906            8 :     async fn test_read_at_max_lsn_algorithm(
    7907            8 :         name: &'static str,
    7908            8 :         compaction_algorithm: CompactionAlgorithm,
    7909            8 :     ) -> anyhow::Result<()> {
    7910            8 :         let mut harness = TenantHarness::create(name).await?;
    7911            8 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7912            8 :             kind: compaction_algorithm,
    7913            8 :         });
    7914            8 :         let (tenant, ctx) = harness.load().await;
    7915            8 :         let tline = tenant
    7916            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7917            8 :             .await?;
    7918              : 
    7919            8 :         let lsn = Lsn(0x10);
    7920            8 :         let compact = false;
    7921            8 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7922              : 
    7923            8 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7924            8 :         let read_lsn = Lsn(u64::MAX - 1);
    7925              : 
    7926            8 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7927            8 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7928              : 
    7929            8 :         Ok(())
    7930            8 :     }
    7931              : 
    7932              :     #[tokio::test]
    7933            4 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7934            4 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7935            4 :         let (tenant, ctx) = harness.load().await;
    7936            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7937            4 :         let tline = tenant
    7938            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7939            4 :             .await?;
    7940            4 : 
    7941            4 :         const NUM_KEYS: usize = 1000;
    7942            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7943            4 : 
    7944            4 :         let cancel = CancellationToken::new();
    7945            4 : 
    7946            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7947            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7948            4 :         let mut test_key = base_key;
    7949            4 : 
    7950            4 :         // Track when each page was last modified. Used to assert that
    7951            4 :         // a read sees the latest page version.
    7952            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7953            4 : 
    7954            4 :         let mut lsn = Lsn(0x10);
    7955            4 :         #[allow(clippy::needless_range_loop)]
    7956         4004 :         for blknum in 0..NUM_KEYS {
    7957         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7958         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7959         4000 :             let mut writer = tline.writer().await;
    7960         4000 :             writer
    7961         4000 :                 .put(
    7962         4000 :                     test_key,
    7963         4000 :                     lsn,
    7964         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7965         4000 :                     &ctx,
    7966         4000 :                 )
    7967         4000 :                 .await?;
    7968         4000 :             writer.finish_write(lsn);
    7969         4000 :             updated[blknum] = lsn;
    7970         4000 :             drop(writer);
    7971            4 :         }
    7972            4 : 
    7973            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7974            4 : 
    7975           48 :         for iter in 0..=10 {
    7976            4 :             // Read all the blocks
    7977        44000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7978        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7979        44000 :                 assert_eq!(
    7980        44000 :                     tline.get(test_key, lsn, &ctx).await?,
    7981        44000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7982            4 :                 );
    7983            4 :             }
    7984            4 : 
    7985           44 :             let mut cnt = 0;
    7986           44 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    7987            4 : 
    7988        44000 :             for (key, value) in tline
    7989           44 :                 .get_vectored_impl(
    7990           44 :                     query,
    7991           44 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7992           44 :                     &ctx,
    7993           44 :                 )
    7994           44 :                 .await?
    7995            4 :             {
    7996        44000 :                 let blknum = key.field6 as usize;
    7997        44000 :                 let value = value?;
    7998        44000 :                 assert!(blknum % STEP == 0);
    7999        44000 :                 let blknum = blknum / STEP;
    8000        44000 :                 assert_eq!(
    8001        44000 :                     value,
    8002        44000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8003        44000 :                 );
    8004        44000 :                 cnt += 1;
    8005            4 :             }
    8006            4 : 
    8007           44 :             assert_eq!(cnt, NUM_KEYS);
    8008            4 : 
    8009        44044 :             for _ in 0..NUM_KEYS {
    8010        44000 :                 lsn = Lsn(lsn.0 + 0x10);
    8011        44000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8012        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    8013        44000 :                 let mut writer = tline.writer().await;
    8014        44000 :                 writer
    8015        44000 :                     .put(
    8016        44000 :                         test_key,
    8017        44000 :                         lsn,
    8018        44000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8019        44000 :                         &ctx,
    8020        44000 :                     )
    8021        44000 :                     .await?;
    8022        44000 :                 writer.finish_write(lsn);
    8023        44000 :                 drop(writer);
    8024        44000 :                 updated[blknum] = lsn;
    8025            4 :             }
    8026            4 : 
    8027            4 :             // Perform two cycles of flush, compact, and GC
    8028          132 :             for round in 0..2 {
    8029           88 :                 tline.freeze_and_flush().await?;
    8030           88 :                 tline
    8031           88 :                     .compact(
    8032           88 :                         &cancel,
    8033           88 :                         if iter % 5 == 0 && round == 0 {
    8034           12 :                             let mut flags = EnumSet::new();
    8035           12 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8036           12 :                             flags.insert(CompactFlags::ForceRepartition);
    8037           12 :                             flags
    8038            4 :                         } else {
    8039           76 :                             EnumSet::empty()
    8040            4 :                         },
    8041           88 :                         &ctx,
    8042           88 :                     )
    8043           88 :                     .await?;
    8044           88 :                 tenant
    8045           88 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8046           88 :                     .await?;
    8047            4 :             }
    8048            4 :         }
    8049            4 : 
    8050            4 :         Ok(())
    8051            4 :     }
    8052              : 
    8053              :     #[tokio::test]
    8054            4 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8055            4 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8056            4 :         let (tenant, ctx) = harness.load().await;
    8057            4 :         let tline = tenant
    8058            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8059            4 :             .await?;
    8060            4 : 
    8061            4 :         let cancel = CancellationToken::new();
    8062            4 : 
    8063            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8064            4 :         base_key.field1 = AUX_KEY_PREFIX;
    8065            4 :         let test_key = base_key;
    8066            4 :         let mut lsn = Lsn(0x10);
    8067            4 : 
    8068           84 :         for _ in 0..20 {
    8069           80 :             lsn = Lsn(lsn.0 + 0x10);
    8070           80 :             let mut writer = tline.writer().await;
    8071           80 :             writer
    8072           80 :                 .put(
    8073           80 :                     test_key,
    8074           80 :                     lsn,
    8075           80 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8076           80 :                     &ctx,
    8077           80 :                 )
    8078           80 :                 .await?;
    8079           80 :             writer.finish_write(lsn);
    8080           80 :             drop(writer);
    8081           80 :             tline.freeze_and_flush().await?; // force create a delta layer
    8082            4 :         }
    8083            4 : 
    8084            4 :         let before_num_l0_delta_files =
    8085            4 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    8086            4 : 
    8087            4 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8088            4 : 
    8089            4 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    8090            4 : 
    8091            4 :         assert!(
    8092            4 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8093            4 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8094            4 :         );
    8095            4 : 
    8096            4 :         assert_eq!(
    8097            4 :             tline.get(test_key, lsn, &ctx).await?,
    8098            4 :             test_img(&format!("{} at {}", 0, lsn))
    8099            4 :         );
    8100            4 : 
    8101            4 :         Ok(())
    8102            4 :     }
    8103              : 
    8104              :     #[tokio::test]
    8105            4 :     async fn test_aux_file_e2e() {
    8106            4 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8107            4 : 
    8108            4 :         let (tenant, ctx) = harness.load().await;
    8109            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8110            4 : 
    8111            4 :         let mut lsn = Lsn(0x08);
    8112            4 : 
    8113            4 :         let tline: Arc<Timeline> = tenant
    8114            4 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8115            4 :             .await
    8116            4 :             .unwrap();
    8117            4 : 
    8118            4 :         {
    8119            4 :             lsn += 8;
    8120            4 :             let mut modification = tline.begin_modification(lsn);
    8121            4 :             modification
    8122            4 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8123            4 :                 .await
    8124            4 :                 .unwrap();
    8125            4 :             modification.commit(&ctx).await.unwrap();
    8126            4 :         }
    8127            4 : 
    8128            4 :         // we can read everything from the storage
    8129            4 :         let files = tline
    8130            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8131            4 :             .await
    8132            4 :             .unwrap();
    8133            4 :         assert_eq!(
    8134            4 :             files.get("pg_logical/mappings/test1"),
    8135            4 :             Some(&bytes::Bytes::from_static(b"first"))
    8136            4 :         );
    8137            4 : 
    8138            4 :         {
    8139            4 :             lsn += 8;
    8140            4 :             let mut modification = tline.begin_modification(lsn);
    8141            4 :             modification
    8142            4 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8143            4 :                 .await
    8144            4 :                 .unwrap();
    8145            4 :             modification.commit(&ctx).await.unwrap();
    8146            4 :         }
    8147            4 : 
    8148            4 :         let files = tline
    8149            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8150            4 :             .await
    8151            4 :             .unwrap();
    8152            4 :         assert_eq!(
    8153            4 :             files.get("pg_logical/mappings/test2"),
    8154            4 :             Some(&bytes::Bytes::from_static(b"second"))
    8155            4 :         );
    8156            4 : 
    8157            4 :         let child = tenant
    8158            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8159            4 :             .await
    8160            4 :             .unwrap();
    8161            4 : 
    8162            4 :         let files = child
    8163            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8164            4 :             .await
    8165            4 :             .unwrap();
    8166            4 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8167            4 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8168            4 :     }
    8169              : 
    8170              :     #[tokio::test]
    8171            4 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8172            4 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8173            4 :         let (tenant, ctx) = harness.load().await;
    8174            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8175            4 :         let tline = tenant
    8176            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8177            4 :             .await?;
    8178            4 : 
    8179            4 :         const NUM_KEYS: usize = 1000;
    8180            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8181            4 : 
    8182            4 :         let cancel = CancellationToken::new();
    8183            4 : 
    8184            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8185            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8186            4 :         let mut test_key = base_key;
    8187            4 :         let mut lsn = Lsn(0x10);
    8188            4 : 
    8189           16 :         async fn scan_with_statistics(
    8190           16 :             tline: &Timeline,
    8191           16 :             keyspace: &KeySpace,
    8192           16 :             lsn: Lsn,
    8193           16 :             ctx: &RequestContext,
    8194           16 :             io_concurrency: IoConcurrency,
    8195           16 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8196           16 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8197           16 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8198           16 :             let res = tline
    8199           16 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8200           16 :                 .await?;
    8201           16 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8202           16 :         }
    8203            4 : 
    8204         4004 :         for blknum in 0..NUM_KEYS {
    8205         4000 :             lsn = Lsn(lsn.0 + 0x10);
    8206         4000 :             test_key.field6 = (blknum * STEP) as u32;
    8207         4000 :             let mut writer = tline.writer().await;
    8208         4000 :             writer
    8209         4000 :                 .put(
    8210         4000 :                     test_key,
    8211         4000 :                     lsn,
    8212         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8213         4000 :                     &ctx,
    8214         4000 :                 )
    8215         4000 :                 .await?;
    8216         4000 :             writer.finish_write(lsn);
    8217         4000 :             drop(writer);
    8218            4 :         }
    8219            4 : 
    8220            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8221            4 : 
    8222           44 :         for iter in 1..=10 {
    8223        40040 :             for _ in 0..NUM_KEYS {
    8224        40000 :                 lsn = Lsn(lsn.0 + 0x10);
    8225        40000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8226        40000 :                 test_key.field6 = (blknum * STEP) as u32;
    8227        40000 :                 let mut writer = tline.writer().await;
    8228        40000 :                 writer
    8229        40000 :                     .put(
    8230        40000 :                         test_key,
    8231        40000 :                         lsn,
    8232        40000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8233        40000 :                         &ctx,
    8234        40000 :                     )
    8235        40000 :                     .await?;
    8236        40000 :                 writer.finish_write(lsn);
    8237        40000 :                 drop(writer);
    8238            4 :             }
    8239            4 : 
    8240           40 :             tline.freeze_and_flush().await?;
    8241            4 : 
    8242           40 :             if iter % 5 == 0 {
    8243            8 :                 let (_, before_delta_file_accessed) =
    8244            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    8245            8 :                         .await?;
    8246            8 :                 tline
    8247            8 :                     .compact(
    8248            8 :                         &cancel,
    8249            8 :                         {
    8250            8 :                             let mut flags = EnumSet::new();
    8251            8 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8252            8 :                             flags.insert(CompactFlags::ForceRepartition);
    8253            8 :                             flags
    8254            8 :                         },
    8255            8 :                         &ctx,
    8256            8 :                     )
    8257            8 :                     .await?;
    8258            8 :                 let (_, after_delta_file_accessed) =
    8259            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    8260            8 :                         .await?;
    8261            8 :                 assert!(
    8262            8 :                     after_delta_file_accessed < before_delta_file_accessed,
    8263            4 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8264            4 :                 );
    8265            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.
    8266            8 :                 assert!(
    8267            8 :                     after_delta_file_accessed <= 2,
    8268            4 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8269            4 :                 );
    8270           32 :             }
    8271            4 :         }
    8272            4 : 
    8273            4 :         Ok(())
    8274            4 :     }
    8275              : 
    8276              :     #[tokio::test]
    8277            4 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8278            4 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8279            4 :         let (tenant, ctx) = harness.load().await;
    8280            4 : 
    8281            4 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8282            4 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8283            4 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8284            4 : 
    8285            4 :         let tline = tenant
    8286            4 :             .create_test_timeline_with_layers(
    8287            4 :                 TIMELINE_ID,
    8288            4 :                 Lsn(0x10),
    8289            4 :                 DEFAULT_PG_VERSION,
    8290            4 :                 &ctx,
    8291            4 :                 Vec::new(), // in-memory layers
    8292            4 :                 Vec::new(), // delta layers
    8293            4 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8294            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
    8295            4 :             )
    8296            4 :             .await?;
    8297            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8298            4 : 
    8299            4 :         let child = tenant
    8300            4 :             .branch_timeline_test_with_layers(
    8301            4 :                 &tline,
    8302            4 :                 NEW_TIMELINE_ID,
    8303            4 :                 Some(Lsn(0x20)),
    8304            4 :                 &ctx,
    8305            4 :                 Vec::new(), // delta layers
    8306            4 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8307            4 :                 Lsn(0x30),
    8308            4 :             )
    8309            4 :             .await
    8310            4 :             .unwrap();
    8311            4 : 
    8312            4 :         let lsn = Lsn(0x30);
    8313            4 : 
    8314            4 :         // test vectored get on parent timeline
    8315            4 :         assert_eq!(
    8316            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8317            4 :             Some(test_img("data key 1"))
    8318            4 :         );
    8319            4 :         assert!(
    8320            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8321            4 :                 .await
    8322            4 :                 .unwrap_err()
    8323            4 :                 .is_missing_key_error()
    8324            4 :         );
    8325            4 :         assert!(
    8326            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8327            4 :                 .await
    8328            4 :                 .unwrap_err()
    8329            4 :                 .is_missing_key_error()
    8330            4 :         );
    8331            4 : 
    8332            4 :         // test vectored get on child timeline
    8333            4 :         assert_eq!(
    8334            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8335            4 :             Some(test_img("data key 1"))
    8336            4 :         );
    8337            4 :         assert_eq!(
    8338            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8339            4 :             Some(test_img("data key 2"))
    8340            4 :         );
    8341            4 :         assert!(
    8342            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8343            4 :                 .await
    8344            4 :                 .unwrap_err()
    8345            4 :                 .is_missing_key_error()
    8346            4 :         );
    8347            4 : 
    8348            4 :         Ok(())
    8349            4 :     }
    8350              : 
    8351              :     #[tokio::test]
    8352            4 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8353            4 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8354            4 :         let (tenant, ctx) = harness.load().await;
    8355            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8356            4 : 
    8357            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8358            4 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8359            4 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8360            4 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8361            4 : 
    8362            4 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8363            4 :         let base_inherited_key_child =
    8364            4 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8365            4 :         let base_inherited_key_nonexist =
    8366            4 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8367            4 :         let base_inherited_key_overwrite =
    8368            4 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8369            4 : 
    8370            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8371            4 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8372            4 : 
    8373            4 :         let tline = tenant
    8374            4 :             .create_test_timeline_with_layers(
    8375            4 :                 TIMELINE_ID,
    8376            4 :                 Lsn(0x10),
    8377            4 :                 DEFAULT_PG_VERSION,
    8378            4 :                 &ctx,
    8379            4 :                 Vec::new(), // in-memory layers
    8380            4 :                 Vec::new(), // delta layers
    8381            4 :                 vec![(
    8382            4 :                     Lsn(0x20),
    8383            4 :                     vec![
    8384            4 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8385            4 :                         (
    8386            4 :                             base_inherited_key_overwrite,
    8387            4 :                             test_img("metadata key overwrite 1a"),
    8388            4 :                         ),
    8389            4 :                         (base_key, test_img("metadata key 1")),
    8390            4 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8391            4 :                     ],
    8392            4 :                 )], // image layers
    8393            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
    8394            4 :             )
    8395            4 :             .await?;
    8396            4 : 
    8397            4 :         let child = tenant
    8398            4 :             .branch_timeline_test_with_layers(
    8399            4 :                 &tline,
    8400            4 :                 NEW_TIMELINE_ID,
    8401            4 :                 Some(Lsn(0x20)),
    8402            4 :                 &ctx,
    8403            4 :                 Vec::new(), // delta layers
    8404            4 :                 vec![(
    8405            4 :                     Lsn(0x30),
    8406            4 :                     vec![
    8407            4 :                         (
    8408            4 :                             base_inherited_key_child,
    8409            4 :                             test_img("metadata inherited key 2"),
    8410            4 :                         ),
    8411            4 :                         (
    8412            4 :                             base_inherited_key_overwrite,
    8413            4 :                             test_img("metadata key overwrite 2a"),
    8414            4 :                         ),
    8415            4 :                         (base_key_child, test_img("metadata key 2")),
    8416            4 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8417            4 :                     ],
    8418            4 :                 )], // image layers
    8419            4 :                 Lsn(0x30),
    8420            4 :             )
    8421            4 :             .await
    8422            4 :             .unwrap();
    8423            4 : 
    8424            4 :         let lsn = Lsn(0x30);
    8425            4 : 
    8426            4 :         // test vectored get on parent timeline
    8427            4 :         assert_eq!(
    8428            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8429            4 :             Some(test_img("metadata key 1"))
    8430            4 :         );
    8431            4 :         assert_eq!(
    8432            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8433            4 :             None
    8434            4 :         );
    8435            4 :         assert_eq!(
    8436            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8437            4 :             None
    8438            4 :         );
    8439            4 :         assert_eq!(
    8440            4 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8441            4 :             Some(test_img("metadata key overwrite 1b"))
    8442            4 :         );
    8443            4 :         assert_eq!(
    8444            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8445            4 :             Some(test_img("metadata inherited key 1"))
    8446            4 :         );
    8447            4 :         assert_eq!(
    8448            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8449            4 :             None
    8450            4 :         );
    8451            4 :         assert_eq!(
    8452            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8453            4 :             None
    8454            4 :         );
    8455            4 :         assert_eq!(
    8456            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8457            4 :             Some(test_img("metadata key overwrite 1a"))
    8458            4 :         );
    8459            4 : 
    8460            4 :         // test vectored get on child timeline
    8461            4 :         assert_eq!(
    8462            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8463            4 :             None
    8464            4 :         );
    8465            4 :         assert_eq!(
    8466            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8467            4 :             Some(test_img("metadata key 2"))
    8468            4 :         );
    8469            4 :         assert_eq!(
    8470            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8471            4 :             None
    8472            4 :         );
    8473            4 :         assert_eq!(
    8474            4 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8475            4 :             Some(test_img("metadata inherited key 1"))
    8476            4 :         );
    8477            4 :         assert_eq!(
    8478            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8479            4 :             Some(test_img("metadata inherited key 2"))
    8480            4 :         );
    8481            4 :         assert_eq!(
    8482            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8483            4 :             None
    8484            4 :         );
    8485            4 :         assert_eq!(
    8486            4 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8487            4 :             Some(test_img("metadata key overwrite 2b"))
    8488            4 :         );
    8489            4 :         assert_eq!(
    8490            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8491            4 :             Some(test_img("metadata key overwrite 2a"))
    8492            4 :         );
    8493            4 : 
    8494            4 :         // test vectored scan on parent timeline
    8495            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8496            4 :         let query =
    8497            4 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8498            4 :         let res = tline
    8499            4 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8500            4 :             .await?;
    8501            4 : 
    8502            4 :         assert_eq!(
    8503            4 :             res.into_iter()
    8504           16 :                 .map(|(k, v)| (k, v.unwrap()))
    8505            4 :                 .collect::<Vec<_>>(),
    8506            4 :             vec![
    8507            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8508            4 :                 (
    8509            4 :                     base_inherited_key_overwrite,
    8510            4 :                     test_img("metadata key overwrite 1a")
    8511            4 :                 ),
    8512            4 :                 (base_key, test_img("metadata key 1")),
    8513            4 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8514            4 :             ]
    8515            4 :         );
    8516            4 : 
    8517            4 :         // test vectored scan on child timeline
    8518            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8519            4 :         let query =
    8520            4 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8521            4 :         let res = child
    8522            4 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8523            4 :             .await?;
    8524            4 : 
    8525            4 :         assert_eq!(
    8526            4 :             res.into_iter()
    8527           20 :                 .map(|(k, v)| (k, v.unwrap()))
    8528            4 :                 .collect::<Vec<_>>(),
    8529            4 :             vec![
    8530            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8531            4 :                 (
    8532            4 :                     base_inherited_key_child,
    8533            4 :                     test_img("metadata inherited key 2")
    8534            4 :                 ),
    8535            4 :                 (
    8536            4 :                     base_inherited_key_overwrite,
    8537            4 :                     test_img("metadata key overwrite 2a")
    8538            4 :                 ),
    8539            4 :                 (base_key_child, test_img("metadata key 2")),
    8540            4 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8541            4 :             ]
    8542            4 :         );
    8543            4 : 
    8544            4 :         Ok(())
    8545            4 :     }
    8546              : 
    8547          112 :     async fn get_vectored_impl_wrapper(
    8548          112 :         tline: &Arc<Timeline>,
    8549          112 :         key: Key,
    8550          112 :         lsn: Lsn,
    8551          112 :         ctx: &RequestContext,
    8552          112 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8553          112 :         let io_concurrency =
    8554          112 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    8555          112 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8556          112 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8557          112 :         let mut res = tline
    8558          112 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8559          112 :             .await?;
    8560          100 :         Ok(res.pop_last().map(|(k, v)| {
    8561           64 :             assert_eq!(k, key);
    8562           64 :             v.unwrap()
    8563          100 :         }))
    8564          112 :     }
    8565              : 
    8566              :     #[tokio::test]
    8567            4 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8568            4 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8569            4 :         let (tenant, ctx) = harness.load().await;
    8570            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8571            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8572            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8573            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8574            4 : 
    8575            4 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8576            4 :         // Lsn 0x30 key0, key3, no key1+key2
    8577            4 :         // Lsn 0x20 key1+key2 tomestones
    8578            4 :         // Lsn 0x10 key1 in image, key2 in delta
    8579            4 :         let tline = tenant
    8580            4 :             .create_test_timeline_with_layers(
    8581            4 :                 TIMELINE_ID,
    8582            4 :                 Lsn(0x10),
    8583            4 :                 DEFAULT_PG_VERSION,
    8584            4 :                 &ctx,
    8585            4 :                 Vec::new(), // in-memory layers
    8586            4 :                 // delta layers
    8587            4 :                 vec![
    8588            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8589            4 :                         Lsn(0x10)..Lsn(0x20),
    8590            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8591            4 :                     ),
    8592            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8593            4 :                         Lsn(0x20)..Lsn(0x30),
    8594            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8595            4 :                     ),
    8596            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8597            4 :                         Lsn(0x20)..Lsn(0x30),
    8598            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8599            4 :                     ),
    8600            4 :                 ],
    8601            4 :                 // image layers
    8602            4 :                 vec![
    8603            4 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8604            4 :                     (
    8605            4 :                         Lsn(0x30),
    8606            4 :                         vec![
    8607            4 :                             (key0, test_img("metadata key 0")),
    8608            4 :                             (key3, test_img("metadata key 3")),
    8609            4 :                         ],
    8610            4 :                     ),
    8611            4 :                 ],
    8612            4 :                 Lsn(0x30),
    8613            4 :             )
    8614            4 :             .await?;
    8615            4 : 
    8616            4 :         let lsn = Lsn(0x30);
    8617            4 :         let old_lsn = Lsn(0x20);
    8618            4 : 
    8619            4 :         assert_eq!(
    8620            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8621            4 :             Some(test_img("metadata key 0"))
    8622            4 :         );
    8623            4 :         assert_eq!(
    8624            4 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8625            4 :             None,
    8626            4 :         );
    8627            4 :         assert_eq!(
    8628            4 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8629            4 :             None,
    8630            4 :         );
    8631            4 :         assert_eq!(
    8632            4 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8633            4 :             Some(Bytes::new()),
    8634            4 :         );
    8635            4 :         assert_eq!(
    8636            4 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8637            4 :             Some(Bytes::new()),
    8638            4 :         );
    8639            4 :         assert_eq!(
    8640            4 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8641            4 :             Some(test_img("metadata key 3"))
    8642            4 :         );
    8643            4 : 
    8644            4 :         Ok(())
    8645            4 :     }
    8646              : 
    8647              :     #[tokio::test]
    8648            4 :     async fn test_metadata_tombstone_image_creation() {
    8649            4 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8650            4 :             .await
    8651            4 :             .unwrap();
    8652            4 :         let (tenant, ctx) = harness.load().await;
    8653            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8654            4 : 
    8655            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8656            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8657            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8658            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8659            4 : 
    8660            4 :         let tline = tenant
    8661            4 :             .create_test_timeline_with_layers(
    8662            4 :                 TIMELINE_ID,
    8663            4 :                 Lsn(0x10),
    8664            4 :                 DEFAULT_PG_VERSION,
    8665            4 :                 &ctx,
    8666            4 :                 Vec::new(), // in-memory layers
    8667            4 :                 // delta layers
    8668            4 :                 vec![
    8669            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8670            4 :                         Lsn(0x10)..Lsn(0x20),
    8671            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8672            4 :                     ),
    8673            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8674            4 :                         Lsn(0x20)..Lsn(0x30),
    8675            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8676            4 :                     ),
    8677            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8678            4 :                         Lsn(0x20)..Lsn(0x30),
    8679            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8680            4 :                     ),
    8681            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8682            4 :                         Lsn(0x30)..Lsn(0x40),
    8683            4 :                         vec![
    8684            4 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8685            4 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8686            4 :                         ],
    8687            4 :                     ),
    8688            4 :                 ],
    8689            4 :                 // image layers
    8690            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8691            4 :                 Lsn(0x40),
    8692            4 :             )
    8693            4 :             .await
    8694            4 :             .unwrap();
    8695            4 : 
    8696            4 :         let cancel = CancellationToken::new();
    8697            4 : 
    8698            4 :         tline
    8699            4 :             .compact(
    8700            4 :                 &cancel,
    8701            4 :                 {
    8702            4 :                     let mut flags = EnumSet::new();
    8703            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8704            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8705            4 :                     flags
    8706            4 :                 },
    8707            4 :                 &ctx,
    8708            4 :             )
    8709            4 :             .await
    8710            4 :             .unwrap();
    8711            4 : 
    8712            4 :         // Image layers are created at last_record_lsn
    8713            4 :         let images = tline
    8714            4 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8715            4 :             .await
    8716            4 :             .unwrap()
    8717            4 :             .into_iter()
    8718           36 :             .filter(|(k, _)| k.is_metadata_key())
    8719            4 :             .collect::<Vec<_>>();
    8720            4 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8721            4 :     }
    8722              : 
    8723              :     #[tokio::test]
    8724            4 :     async fn test_metadata_tombstone_empty_image_creation() {
    8725            4 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8726            4 :             .await
    8727            4 :             .unwrap();
    8728            4 :         let (tenant, ctx) = harness.load().await;
    8729            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8730            4 : 
    8731            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8732            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8733            4 : 
    8734            4 :         let tline = tenant
    8735            4 :             .create_test_timeline_with_layers(
    8736            4 :                 TIMELINE_ID,
    8737            4 :                 Lsn(0x10),
    8738            4 :                 DEFAULT_PG_VERSION,
    8739            4 :                 &ctx,
    8740            4 :                 Vec::new(), // in-memory layers
    8741            4 :                 // delta layers
    8742            4 :                 vec![
    8743            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8744            4 :                         Lsn(0x10)..Lsn(0x20),
    8745            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8746            4 :                     ),
    8747            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8748            4 :                         Lsn(0x20)..Lsn(0x30),
    8749            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8750            4 :                     ),
    8751            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8752            4 :                         Lsn(0x20)..Lsn(0x30),
    8753            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8754            4 :                     ),
    8755            4 :                 ],
    8756            4 :                 // image layers
    8757            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8758            4 :                 Lsn(0x30),
    8759            4 :             )
    8760            4 :             .await
    8761            4 :             .unwrap();
    8762            4 : 
    8763            4 :         let cancel = CancellationToken::new();
    8764            4 : 
    8765            4 :         tline
    8766            4 :             .compact(
    8767            4 :                 &cancel,
    8768            4 :                 {
    8769            4 :                     let mut flags = EnumSet::new();
    8770            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8771            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8772            4 :                     flags
    8773            4 :                 },
    8774            4 :                 &ctx,
    8775            4 :             )
    8776            4 :             .await
    8777            4 :             .unwrap();
    8778            4 : 
    8779            4 :         // Image layers are created at last_record_lsn
    8780            4 :         let images = tline
    8781            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8782            4 :             .await
    8783            4 :             .unwrap()
    8784            4 :             .into_iter()
    8785           28 :             .filter(|(k, _)| k.is_metadata_key())
    8786            4 :             .collect::<Vec<_>>();
    8787            4 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8788            4 :     }
    8789              : 
    8790              :     #[tokio::test]
    8791            4 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8792            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8793            4 :         let (tenant, ctx) = harness.load().await;
    8794            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8795            4 : 
    8796          204 :         fn get_key(id: u32) -> Key {
    8797          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8798          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8799          204 :             key.field6 = id;
    8800          204 :             key
    8801          204 :         }
    8802            4 : 
    8803            4 :         // We create
    8804            4 :         // - one bottom-most image layer,
    8805            4 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8806            4 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8807            4 :         // - a delta layer D3 above the horizon.
    8808            4 :         //
    8809            4 :         //                             | D3 |
    8810            4 :         //  | D1 |
    8811            4 :         // -|    |-- gc horizon -----------------
    8812            4 :         //  |    |                | D2 |
    8813            4 :         // --------- img layer ------------------
    8814            4 :         //
    8815            4 :         // What we should expact from this compaction is:
    8816            4 :         //                             | D3 |
    8817            4 :         //  | Part of D1 |
    8818            4 :         // --------- img layer with D1+D2 at GC horizon------------------
    8819            4 : 
    8820            4 :         // img layer at 0x10
    8821            4 :         let img_layer = (0..10)
    8822           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8823            4 :             .collect_vec();
    8824            4 : 
    8825            4 :         let delta1 = vec![
    8826            4 :             (
    8827            4 :                 get_key(1),
    8828            4 :                 Lsn(0x20),
    8829            4 :                 Value::Image(Bytes::from("value 1@0x20")),
    8830            4 :             ),
    8831            4 :             (
    8832            4 :                 get_key(2),
    8833            4 :                 Lsn(0x30),
    8834            4 :                 Value::Image(Bytes::from("value 2@0x30")),
    8835            4 :             ),
    8836            4 :             (
    8837            4 :                 get_key(3),
    8838            4 :                 Lsn(0x40),
    8839            4 :                 Value::Image(Bytes::from("value 3@0x40")),
    8840            4 :             ),
    8841            4 :         ];
    8842            4 :         let delta2 = vec![
    8843            4 :             (
    8844            4 :                 get_key(5),
    8845            4 :                 Lsn(0x20),
    8846            4 :                 Value::Image(Bytes::from("value 5@0x20")),
    8847            4 :             ),
    8848            4 :             (
    8849            4 :                 get_key(6),
    8850            4 :                 Lsn(0x20),
    8851            4 :                 Value::Image(Bytes::from("value 6@0x20")),
    8852            4 :             ),
    8853            4 :         ];
    8854            4 :         let delta3 = vec![
    8855            4 :             (
    8856            4 :                 get_key(8),
    8857            4 :                 Lsn(0x48),
    8858            4 :                 Value::Image(Bytes::from("value 8@0x48")),
    8859            4 :             ),
    8860            4 :             (
    8861            4 :                 get_key(9),
    8862            4 :                 Lsn(0x48),
    8863            4 :                 Value::Image(Bytes::from("value 9@0x48")),
    8864            4 :             ),
    8865            4 :         ];
    8866            4 : 
    8867            4 :         let tline = tenant
    8868            4 :             .create_test_timeline_with_layers(
    8869            4 :                 TIMELINE_ID,
    8870            4 :                 Lsn(0x10),
    8871            4 :                 DEFAULT_PG_VERSION,
    8872            4 :                 &ctx,
    8873            4 :                 Vec::new(), // in-memory layers
    8874            4 :                 vec![
    8875            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8876            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8877            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8878            4 :                 ], // delta layers
    8879            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8880            4 :                 Lsn(0x50),
    8881            4 :             )
    8882            4 :             .await?;
    8883            4 :         {
    8884            4 :             tline
    8885            4 :                 .applied_gc_cutoff_lsn
    8886            4 :                 .lock_for_write()
    8887            4 :                 .store_and_unlock(Lsn(0x30))
    8888            4 :                 .wait()
    8889            4 :                 .await;
    8890            4 :             // Update GC info
    8891            4 :             let mut guard = tline.gc_info.write().unwrap();
    8892            4 :             guard.cutoffs.time = Lsn(0x30);
    8893            4 :             guard.cutoffs.space = Lsn(0x30);
    8894            4 :         }
    8895            4 : 
    8896            4 :         let expected_result = [
    8897            4 :             Bytes::from_static(b"value 0@0x10"),
    8898            4 :             Bytes::from_static(b"value 1@0x20"),
    8899            4 :             Bytes::from_static(b"value 2@0x30"),
    8900            4 :             Bytes::from_static(b"value 3@0x40"),
    8901            4 :             Bytes::from_static(b"value 4@0x10"),
    8902            4 :             Bytes::from_static(b"value 5@0x20"),
    8903            4 :             Bytes::from_static(b"value 6@0x20"),
    8904            4 :             Bytes::from_static(b"value 7@0x10"),
    8905            4 :             Bytes::from_static(b"value 8@0x48"),
    8906            4 :             Bytes::from_static(b"value 9@0x48"),
    8907            4 :         ];
    8908            4 : 
    8909           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8910           40 :             assert_eq!(
    8911           40 :                 tline
    8912           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8913           40 :                     .await
    8914           40 :                     .unwrap(),
    8915            4 :                 expected
    8916            4 :             );
    8917            4 :         }
    8918            4 : 
    8919            4 :         let cancel = CancellationToken::new();
    8920            4 :         tline
    8921            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8922            4 :             .await
    8923            4 :             .unwrap();
    8924            4 : 
    8925           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8926           40 :             assert_eq!(
    8927           40 :                 tline
    8928           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8929           40 :                     .await
    8930           40 :                     .unwrap(),
    8931            4 :                 expected
    8932            4 :             );
    8933            4 :         }
    8934            4 : 
    8935            4 :         // Check if the image layer at the GC horizon contains exactly what we want
    8936            4 :         let image_at_gc_horizon = tline
    8937            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8938            4 :             .await
    8939            4 :             .unwrap()
    8940            4 :             .into_iter()
    8941           68 :             .filter(|(k, _)| k.is_metadata_key())
    8942            4 :             .collect::<Vec<_>>();
    8943            4 : 
    8944            4 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8945            4 :         let expected_result = [
    8946            4 :             Bytes::from_static(b"value 0@0x10"),
    8947            4 :             Bytes::from_static(b"value 1@0x20"),
    8948            4 :             Bytes::from_static(b"value 2@0x30"),
    8949            4 :             Bytes::from_static(b"value 3@0x10"),
    8950            4 :             Bytes::from_static(b"value 4@0x10"),
    8951            4 :             Bytes::from_static(b"value 5@0x20"),
    8952            4 :             Bytes::from_static(b"value 6@0x20"),
    8953            4 :             Bytes::from_static(b"value 7@0x10"),
    8954            4 :             Bytes::from_static(b"value 8@0x10"),
    8955            4 :             Bytes::from_static(b"value 9@0x10"),
    8956            4 :         ];
    8957           44 :         for idx in 0..10 {
    8958           40 :             assert_eq!(
    8959           40 :                 image_at_gc_horizon[idx],
    8960           40 :                 (get_key(idx as u32), expected_result[idx].clone())
    8961           40 :             );
    8962            4 :         }
    8963            4 : 
    8964            4 :         // Check if old layers are removed / new layers have the expected LSN
    8965            4 :         let all_layers = inspect_and_sort(&tline, None).await;
    8966            4 :         assert_eq!(
    8967            4 :             all_layers,
    8968            4 :             vec![
    8969            4 :                 // Image layer at GC horizon
    8970            4 :                 PersistentLayerKey {
    8971            4 :                     key_range: Key::MIN..Key::MAX,
    8972            4 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8973            4 :                     is_delta: false
    8974            4 :                 },
    8975            4 :                 // The delta layer below the horizon
    8976            4 :                 PersistentLayerKey {
    8977            4 :                     key_range: get_key(3)..get_key(4),
    8978            4 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8979            4 :                     is_delta: true
    8980            4 :                 },
    8981            4 :                 // The delta3 layer that should not be picked for the compaction
    8982            4 :                 PersistentLayerKey {
    8983            4 :                     key_range: get_key(8)..get_key(10),
    8984            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8985            4 :                     is_delta: true
    8986            4 :                 }
    8987            4 :             ]
    8988            4 :         );
    8989            4 : 
    8990            4 :         // increase GC horizon and compact again
    8991            4 :         {
    8992            4 :             tline
    8993            4 :                 .applied_gc_cutoff_lsn
    8994            4 :                 .lock_for_write()
    8995            4 :                 .store_and_unlock(Lsn(0x40))
    8996            4 :                 .wait()
    8997            4 :                 .await;
    8998            4 :             // Update GC info
    8999            4 :             let mut guard = tline.gc_info.write().unwrap();
    9000            4 :             guard.cutoffs.time = Lsn(0x40);
    9001            4 :             guard.cutoffs.space = Lsn(0x40);
    9002            4 :         }
    9003            4 :         tline
    9004            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9005            4 :             .await
    9006            4 :             .unwrap();
    9007            4 : 
    9008            4 :         Ok(())
    9009            4 :     }
    9010              : 
    9011              :     #[cfg(feature = "testing")]
    9012              :     #[tokio::test]
    9013            4 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9014            4 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9015            4 :         let (tenant, ctx) = harness.load().await;
    9016            4 : 
    9017           68 :         fn get_key(id: u32) -> Key {
    9018           68 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9019           68 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9020           68 :             key.field6 = id;
    9021           68 :             key
    9022           68 :         }
    9023            4 : 
    9024            4 :         let delta1 = vec![
    9025            4 :             (
    9026            4 :                 get_key(1),
    9027            4 :                 Lsn(0x20),
    9028            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9029            4 :             ),
    9030            4 :             (
    9031            4 :                 get_key(1),
    9032            4 :                 Lsn(0x30),
    9033            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9034            4 :             ),
    9035            4 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9036            4 :             (
    9037            4 :                 get_key(2),
    9038            4 :                 Lsn(0x20),
    9039            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9040            4 :             ),
    9041            4 :             (
    9042            4 :                 get_key(2),
    9043            4 :                 Lsn(0x30),
    9044            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9045            4 :             ),
    9046            4 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9047            4 :             (
    9048            4 :                 get_key(3),
    9049            4 :                 Lsn(0x20),
    9050            4 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9051            4 :             ),
    9052            4 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9053            4 :             (
    9054            4 :                 get_key(4),
    9055            4 :                 Lsn(0x20),
    9056            4 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9057            4 :             ),
    9058            4 :             (
    9059            4 :                 get_key(4),
    9060            4 :                 Lsn(0x30),
    9061            4 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9062            4 :             ),
    9063            4 :             (
    9064            4 :                 get_key(5),
    9065            4 :                 Lsn(0x20),
    9066            4 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9067            4 :             ),
    9068            4 :             (
    9069            4 :                 get_key(5),
    9070            4 :                 Lsn(0x30),
    9071            4 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9072            4 :             ),
    9073            4 :         ];
    9074            4 :         let image1 = vec![(get_key(1), "0x10".into())];
    9075            4 : 
    9076            4 :         let tline = tenant
    9077            4 :             .create_test_timeline_with_layers(
    9078            4 :                 TIMELINE_ID,
    9079            4 :                 Lsn(0x10),
    9080            4 :                 DEFAULT_PG_VERSION,
    9081            4 :                 &ctx,
    9082            4 :                 Vec::new(), // in-memory layers
    9083            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9084            4 :                     Lsn(0x10)..Lsn(0x40),
    9085            4 :                     delta1,
    9086            4 :                 )], // delta layers
    9087            4 :                 vec![(Lsn(0x10), image1)], // image layers
    9088            4 :                 Lsn(0x50),
    9089            4 :             )
    9090            4 :             .await?;
    9091            4 : 
    9092            4 :         assert_eq!(
    9093            4 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9094            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    9095            4 :         );
    9096            4 :         assert_eq!(
    9097            4 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9098            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    9099            4 :         );
    9100            4 : 
    9101            4 :         // Need to remove the limit of "Neon WAL redo requires base image".
    9102            4 : 
    9103            4 :         assert_eq!(
    9104            4 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9105            4 :             Bytes::from_static(b"c")
    9106            4 :         );
    9107            4 :         assert_eq!(
    9108            4 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9109            4 :             Bytes::from_static(b"ij")
    9110            4 :         );
    9111            4 : 
    9112            4 :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9113            4 :         // cannot enable this assertion in the unit test.
    9114            4 :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9115            4 : 
    9116            4 :         Ok(())
    9117            4 :     }
    9118              : 
    9119              :     #[tokio::test(start_paused = true)]
    9120            4 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9121            4 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9122            4 :             .await
    9123            4 :             .unwrap()
    9124            4 :             .load()
    9125            4 :             .await;
    9126            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    9127            4 :         // initial transition into AttachedSingle.
    9128            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    9129            4 :         tokio::time::resume();
    9130            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9131            4 : 
    9132            4 :         let end_lsn = Lsn(0x100);
    9133            4 :         let image_layers = (0x20..=0x90)
    9134            4 :             .step_by(0x10)
    9135           32 :             .map(|n| {
    9136           32 :                 (
    9137           32 :                     Lsn(n),
    9138           32 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    9139           32 :                 )
    9140           32 :             })
    9141            4 :             .collect();
    9142            4 : 
    9143            4 :         let timeline = tenant
    9144            4 :             .create_test_timeline_with_layers(
    9145            4 :                 TIMELINE_ID,
    9146            4 :                 Lsn(0x10),
    9147            4 :                 DEFAULT_PG_VERSION,
    9148            4 :                 &ctx,
    9149            4 :                 Vec::new(), // in-memory layers
    9150            4 :                 Vec::new(),
    9151            4 :                 image_layers,
    9152            4 :                 end_lsn,
    9153            4 :             )
    9154            4 :             .await?;
    9155            4 : 
    9156            4 :         let leased_lsns = [0x30, 0x50, 0x70];
    9157            4 :         let mut leases = Vec::new();
    9158           12 :         leased_lsns.iter().for_each(|n| {
    9159           12 :             leases.push(
    9160           12 :                 timeline
    9161           12 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9162           12 :                     .expect("lease request should succeed"),
    9163           12 :             );
    9164           12 :         });
    9165            4 : 
    9166            4 :         let updated_lease_0 = timeline
    9167            4 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9168            4 :             .expect("lease renewal should succeed");
    9169            4 :         assert_eq!(
    9170            4 :             updated_lease_0.valid_until, leases[0].valid_until,
    9171            4 :             " Renewing with shorter lease should not change the lease."
    9172            4 :         );
    9173            4 : 
    9174            4 :         let updated_lease_1 = timeline
    9175            4 :             .renew_lsn_lease(
    9176            4 :                 Lsn(leased_lsns[1]),
    9177            4 :                 timeline.get_lsn_lease_length() * 2,
    9178            4 :                 &ctx,
    9179            4 :             )
    9180            4 :             .expect("lease renewal should succeed");
    9181            4 :         assert!(
    9182            4 :             updated_lease_1.valid_until > leases[1].valid_until,
    9183            4 :             "Renewing with a long lease should renew lease with later expiration time."
    9184            4 :         );
    9185            4 : 
    9186            4 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9187            4 :         info!(
    9188            4 :             "applied_gc_cutoff_lsn: {}",
    9189            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9190            4 :         );
    9191            4 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9192            4 : 
    9193            4 :         let res = tenant
    9194            4 :             .gc_iteration(
    9195            4 :                 Some(TIMELINE_ID),
    9196            4 :                 0,
    9197            4 :                 Duration::ZERO,
    9198            4 :                 &CancellationToken::new(),
    9199            4 :                 &ctx,
    9200            4 :             )
    9201            4 :             .await
    9202            4 :             .unwrap();
    9203            4 : 
    9204            4 :         // Keeping everything <= Lsn(0x80) b/c leases:
    9205            4 :         // 0/10: initdb layer
    9206            4 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9207            4 :         assert_eq!(res.layers_needed_by_leases, 7);
    9208            4 :         // Keeping 0/90 b/c it is the latest layer.
    9209            4 :         assert_eq!(res.layers_not_updated, 1);
    9210            4 :         // Removed 0/80.
    9211            4 :         assert_eq!(res.layers_removed, 1);
    9212            4 : 
    9213            4 :         // Make lease on a already GC-ed LSN.
    9214            4 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9215            4 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9216            4 :         timeline
    9217            4 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9218            4 :             .expect_err("lease request on GC-ed LSN should fail");
    9219            4 : 
    9220            4 :         // Should still be able to renew a currently valid lease
    9221            4 :         // Assumption: original lease to is still valid for 0/50.
    9222            4 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9223            4 :         timeline
    9224            4 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9225            4 :             .expect("lease renewal with validation should succeed");
    9226            4 : 
    9227            4 :         Ok(())
    9228            4 :     }
    9229              : 
    9230              :     #[cfg(feature = "testing")]
    9231              :     #[tokio::test]
    9232            4 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9233            4 :         test_simple_bottom_most_compaction_deltas_helper(
    9234            4 :             "test_simple_bottom_most_compaction_deltas_1",
    9235            4 :             false,
    9236            4 :         )
    9237            4 :         .await
    9238            4 :     }
    9239              : 
    9240              :     #[cfg(feature = "testing")]
    9241              :     #[tokio::test]
    9242            4 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9243            4 :         test_simple_bottom_most_compaction_deltas_helper(
    9244            4 :             "test_simple_bottom_most_compaction_deltas_2",
    9245            4 :             true,
    9246            4 :         )
    9247            4 :         .await
    9248            4 :     }
    9249              : 
    9250              :     #[cfg(feature = "testing")]
    9251            8 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9252            8 :         test_name: &'static str,
    9253            8 :         use_delta_bottom_layer: bool,
    9254            8 :     ) -> anyhow::Result<()> {
    9255            8 :         let harness = TenantHarness::create(test_name).await?;
    9256            8 :         let (tenant, ctx) = harness.load().await;
    9257              : 
    9258          552 :         fn get_key(id: u32) -> Key {
    9259          552 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9260          552 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9261          552 :             key.field6 = id;
    9262          552 :             key
    9263          552 :         }
    9264              : 
    9265              :         // We create
    9266              :         // - one bottom-most image layer,
    9267              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9268              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9269              :         // - a delta layer D3 above the horizon.
    9270              :         //
    9271              :         //                             | D3 |
    9272              :         //  | D1 |
    9273              :         // -|    |-- gc horizon -----------------
    9274              :         //  |    |                | D2 |
    9275              :         // --------- img layer ------------------
    9276              :         //
    9277              :         // What we should expact from this compaction is:
    9278              :         //                             | D3 |
    9279              :         //  | Part of D1 |
    9280              :         // --------- img layer with D1+D2 at GC horizon------------------
    9281              : 
    9282              :         // img layer at 0x10
    9283            8 :         let img_layer = (0..10)
    9284           80 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9285            8 :             .collect_vec();
    9286            8 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9287            8 :         let delta4 = (0..10)
    9288           80 :             .map(|id| {
    9289           80 :                 (
    9290           80 :                     get_key(id),
    9291           80 :                     Lsn(0x08),
    9292           80 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9293           80 :                 )
    9294           80 :             })
    9295            8 :             .collect_vec();
    9296            8 : 
    9297            8 :         let delta1 = vec![
    9298            8 :             (
    9299            8 :                 get_key(1),
    9300            8 :                 Lsn(0x20),
    9301            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9302            8 :             ),
    9303            8 :             (
    9304            8 :                 get_key(2),
    9305            8 :                 Lsn(0x30),
    9306            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9307            8 :             ),
    9308            8 :             (
    9309            8 :                 get_key(3),
    9310            8 :                 Lsn(0x28),
    9311            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9312            8 :             ),
    9313            8 :             (
    9314            8 :                 get_key(3),
    9315            8 :                 Lsn(0x30),
    9316            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9317            8 :             ),
    9318            8 :             (
    9319            8 :                 get_key(3),
    9320            8 :                 Lsn(0x40),
    9321            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9322            8 :             ),
    9323            8 :         ];
    9324            8 :         let delta2 = vec![
    9325            8 :             (
    9326            8 :                 get_key(5),
    9327            8 :                 Lsn(0x20),
    9328            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9329            8 :             ),
    9330            8 :             (
    9331            8 :                 get_key(6),
    9332            8 :                 Lsn(0x20),
    9333            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9334            8 :             ),
    9335            8 :         ];
    9336            8 :         let delta3 = vec![
    9337            8 :             (
    9338            8 :                 get_key(8),
    9339            8 :                 Lsn(0x48),
    9340            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9341            8 :             ),
    9342            8 :             (
    9343            8 :                 get_key(9),
    9344            8 :                 Lsn(0x48),
    9345            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9346            8 :             ),
    9347            8 :         ];
    9348              : 
    9349            8 :         let tline = if use_delta_bottom_layer {
    9350            4 :             tenant
    9351            4 :                 .create_test_timeline_with_layers(
    9352            4 :                     TIMELINE_ID,
    9353            4 :                     Lsn(0x08),
    9354            4 :                     DEFAULT_PG_VERSION,
    9355            4 :                     &ctx,
    9356            4 :                     Vec::new(), // in-memory layers
    9357            4 :                     vec![
    9358            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9359            4 :                             Lsn(0x08)..Lsn(0x10),
    9360            4 :                             delta4,
    9361            4 :                         ),
    9362            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9363            4 :                             Lsn(0x20)..Lsn(0x48),
    9364            4 :                             delta1,
    9365            4 :                         ),
    9366            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9367            4 :                             Lsn(0x20)..Lsn(0x48),
    9368            4 :                             delta2,
    9369            4 :                         ),
    9370            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9371            4 :                             Lsn(0x48)..Lsn(0x50),
    9372            4 :                             delta3,
    9373            4 :                         ),
    9374            4 :                     ], // delta layers
    9375            4 :                     vec![],     // image layers
    9376            4 :                     Lsn(0x50),
    9377            4 :                 )
    9378            4 :                 .await?
    9379              :         } else {
    9380            4 :             tenant
    9381            4 :                 .create_test_timeline_with_layers(
    9382            4 :                     TIMELINE_ID,
    9383            4 :                     Lsn(0x10),
    9384            4 :                     DEFAULT_PG_VERSION,
    9385            4 :                     &ctx,
    9386            4 :                     Vec::new(), // in-memory layers
    9387            4 :                     vec![
    9388            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9389            4 :                             Lsn(0x10)..Lsn(0x48),
    9390            4 :                             delta1,
    9391            4 :                         ),
    9392            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9393            4 :                             Lsn(0x10)..Lsn(0x48),
    9394            4 :                             delta2,
    9395            4 :                         ),
    9396            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9397            4 :                             Lsn(0x48)..Lsn(0x50),
    9398            4 :                             delta3,
    9399            4 :                         ),
    9400            4 :                     ], // delta layers
    9401            4 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9402            4 :                     Lsn(0x50),
    9403            4 :                 )
    9404            4 :                 .await?
    9405              :         };
    9406              :         {
    9407            8 :             tline
    9408            8 :                 .applied_gc_cutoff_lsn
    9409            8 :                 .lock_for_write()
    9410            8 :                 .store_and_unlock(Lsn(0x30))
    9411            8 :                 .wait()
    9412            8 :                 .await;
    9413              :             // Update GC info
    9414            8 :             let mut guard = tline.gc_info.write().unwrap();
    9415            8 :             *guard = GcInfo {
    9416            8 :                 retain_lsns: vec![],
    9417            8 :                 cutoffs: GcCutoffs {
    9418            8 :                     time: Lsn(0x30),
    9419            8 :                     space: Lsn(0x30),
    9420            8 :                 },
    9421            8 :                 leases: Default::default(),
    9422            8 :                 within_ancestor_pitr: false,
    9423            8 :             };
    9424            8 :         }
    9425            8 : 
    9426            8 :         let expected_result = [
    9427            8 :             Bytes::from_static(b"value 0@0x10"),
    9428            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9429            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9430            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9431            8 :             Bytes::from_static(b"value 4@0x10"),
    9432            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9433            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9434            8 :             Bytes::from_static(b"value 7@0x10"),
    9435            8 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9436            8 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9437            8 :         ];
    9438            8 : 
    9439            8 :         let expected_result_at_gc_horizon = [
    9440            8 :             Bytes::from_static(b"value 0@0x10"),
    9441            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9442            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9443            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9444            8 :             Bytes::from_static(b"value 4@0x10"),
    9445            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9446            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9447            8 :             Bytes::from_static(b"value 7@0x10"),
    9448            8 :             Bytes::from_static(b"value 8@0x10"),
    9449            8 :             Bytes::from_static(b"value 9@0x10"),
    9450            8 :         ];
    9451              : 
    9452           88 :         for idx in 0..10 {
    9453           80 :             assert_eq!(
    9454           80 :                 tline
    9455           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9456           80 :                     .await
    9457           80 :                     .unwrap(),
    9458           80 :                 &expected_result[idx]
    9459              :             );
    9460           80 :             assert_eq!(
    9461           80 :                 tline
    9462           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9463           80 :                     .await
    9464           80 :                     .unwrap(),
    9465           80 :                 &expected_result_at_gc_horizon[idx]
    9466              :             );
    9467              :         }
    9468              : 
    9469            8 :         let cancel = CancellationToken::new();
    9470            8 :         tline
    9471            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9472            8 :             .await
    9473            8 :             .unwrap();
    9474              : 
    9475           88 :         for idx in 0..10 {
    9476           80 :             assert_eq!(
    9477           80 :                 tline
    9478           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9479           80 :                     .await
    9480           80 :                     .unwrap(),
    9481           80 :                 &expected_result[idx]
    9482              :             );
    9483           80 :             assert_eq!(
    9484           80 :                 tline
    9485           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9486           80 :                     .await
    9487           80 :                     .unwrap(),
    9488           80 :                 &expected_result_at_gc_horizon[idx]
    9489              :             );
    9490              :         }
    9491              : 
    9492              :         // increase GC horizon and compact again
    9493              :         {
    9494            8 :             tline
    9495            8 :                 .applied_gc_cutoff_lsn
    9496            8 :                 .lock_for_write()
    9497            8 :                 .store_and_unlock(Lsn(0x40))
    9498            8 :                 .wait()
    9499            8 :                 .await;
    9500              :             // Update GC info
    9501            8 :             let mut guard = tline.gc_info.write().unwrap();
    9502            8 :             guard.cutoffs.time = Lsn(0x40);
    9503            8 :             guard.cutoffs.space = Lsn(0x40);
    9504            8 :         }
    9505            8 :         tline
    9506            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9507            8 :             .await
    9508            8 :             .unwrap();
    9509            8 : 
    9510            8 :         Ok(())
    9511            8 :     }
    9512              : 
    9513              :     #[cfg(feature = "testing")]
    9514              :     #[tokio::test]
    9515            4 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9516            4 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9517            4 :         let (tenant, ctx) = harness.load().await;
    9518            4 :         let tline = tenant
    9519            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9520            4 :             .await?;
    9521            4 :         tline.force_advance_lsn(Lsn(0x70));
    9522            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9523            4 :         let history = vec![
    9524            4 :             (
    9525            4 :                 key,
    9526            4 :                 Lsn(0x10),
    9527            4 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9528            4 :             ),
    9529            4 :             (
    9530            4 :                 key,
    9531            4 :                 Lsn(0x20),
    9532            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9533            4 :             ),
    9534            4 :             (
    9535            4 :                 key,
    9536            4 :                 Lsn(0x30),
    9537            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9538            4 :             ),
    9539            4 :             (
    9540            4 :                 key,
    9541            4 :                 Lsn(0x40),
    9542            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9543            4 :             ),
    9544            4 :             (
    9545            4 :                 key,
    9546            4 :                 Lsn(0x50),
    9547            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9548            4 :             ),
    9549            4 :             (
    9550            4 :                 key,
    9551            4 :                 Lsn(0x60),
    9552            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9553            4 :             ),
    9554            4 :             (
    9555            4 :                 key,
    9556            4 :                 Lsn(0x70),
    9557            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9558            4 :             ),
    9559            4 :             (
    9560            4 :                 key,
    9561            4 :                 Lsn(0x80),
    9562            4 :                 Value::Image(Bytes::copy_from_slice(
    9563            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9564            4 :                 )),
    9565            4 :             ),
    9566            4 :             (
    9567            4 :                 key,
    9568            4 :                 Lsn(0x90),
    9569            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9570            4 :             ),
    9571            4 :         ];
    9572            4 :         let res = tline
    9573            4 :             .generate_key_retention(
    9574            4 :                 key,
    9575            4 :                 &history,
    9576            4 :                 Lsn(0x60),
    9577            4 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9578            4 :                 3,
    9579            4 :                 None,
    9580            4 :                 true,
    9581            4 :             )
    9582            4 :             .await
    9583            4 :             .unwrap();
    9584            4 :         let expected_res = KeyHistoryRetention {
    9585            4 :             below_horizon: vec![
    9586            4 :                 (
    9587            4 :                     Lsn(0x20),
    9588            4 :                     KeyLogAtLsn(vec![(
    9589            4 :                         Lsn(0x20),
    9590            4 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9591            4 :                     )]),
    9592            4 :                 ),
    9593            4 :                 (
    9594            4 :                     Lsn(0x40),
    9595            4 :                     KeyLogAtLsn(vec![
    9596            4 :                         (
    9597            4 :                             Lsn(0x30),
    9598            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9599            4 :                         ),
    9600            4 :                         (
    9601            4 :                             Lsn(0x40),
    9602            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9603            4 :                         ),
    9604            4 :                     ]),
    9605            4 :                 ),
    9606            4 :                 (
    9607            4 :                     Lsn(0x50),
    9608            4 :                     KeyLogAtLsn(vec![(
    9609            4 :                         Lsn(0x50),
    9610            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9611            4 :                     )]),
    9612            4 :                 ),
    9613            4 :                 (
    9614            4 :                     Lsn(0x60),
    9615            4 :                     KeyLogAtLsn(vec![(
    9616            4 :                         Lsn(0x60),
    9617            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9618            4 :                     )]),
    9619            4 :                 ),
    9620            4 :             ],
    9621            4 :             above_horizon: KeyLogAtLsn(vec![
    9622            4 :                 (
    9623            4 :                     Lsn(0x70),
    9624            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9625            4 :                 ),
    9626            4 :                 (
    9627            4 :                     Lsn(0x80),
    9628            4 :                     Value::Image(Bytes::copy_from_slice(
    9629            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9630            4 :                     )),
    9631            4 :                 ),
    9632            4 :                 (
    9633            4 :                     Lsn(0x90),
    9634            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9635            4 :                 ),
    9636            4 :             ]),
    9637            4 :         };
    9638            4 :         assert_eq!(res, expected_res);
    9639            4 : 
    9640            4 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9641            4 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9642            4 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9643            4 :         // For example, we have
    9644            4 :         // ```plain
    9645            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9646            4 :         // ```
    9647            4 :         // Now the GC horizon moves up, and we have
    9648            4 :         // ```plain
    9649            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9650            4 :         // ```
    9651            4 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9652            4 :         // We will end up with
    9653            4 :         // ```plain
    9654            4 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9655            4 :         // ```
    9656            4 :         // Now we run the GC-compaction, and this key does not have a full history.
    9657            4 :         // We should be able to handle this partial history and drop everything before the
    9658            4 :         // gc_horizon image.
    9659            4 : 
    9660            4 :         let history = vec![
    9661            4 :             (
    9662            4 :                 key,
    9663            4 :                 Lsn(0x20),
    9664            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9665            4 :             ),
    9666            4 :             (
    9667            4 :                 key,
    9668            4 :                 Lsn(0x30),
    9669            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9670            4 :             ),
    9671            4 :             (
    9672            4 :                 key,
    9673            4 :                 Lsn(0x40),
    9674            4 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9675            4 :             ),
    9676            4 :             (
    9677            4 :                 key,
    9678            4 :                 Lsn(0x50),
    9679            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9680            4 :             ),
    9681            4 :             (
    9682            4 :                 key,
    9683            4 :                 Lsn(0x60),
    9684            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9685            4 :             ),
    9686            4 :             (
    9687            4 :                 key,
    9688            4 :                 Lsn(0x70),
    9689            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9690            4 :             ),
    9691            4 :             (
    9692            4 :                 key,
    9693            4 :                 Lsn(0x80),
    9694            4 :                 Value::Image(Bytes::copy_from_slice(
    9695            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9696            4 :                 )),
    9697            4 :             ),
    9698            4 :             (
    9699            4 :                 key,
    9700            4 :                 Lsn(0x90),
    9701            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9702            4 :             ),
    9703            4 :         ];
    9704            4 :         let res = tline
    9705            4 :             .generate_key_retention(
    9706            4 :                 key,
    9707            4 :                 &history,
    9708            4 :                 Lsn(0x60),
    9709            4 :                 &[Lsn(0x40), Lsn(0x50)],
    9710            4 :                 3,
    9711            4 :                 None,
    9712            4 :                 true,
    9713            4 :             )
    9714            4 :             .await
    9715            4 :             .unwrap();
    9716            4 :         let expected_res = KeyHistoryRetention {
    9717            4 :             below_horizon: vec![
    9718            4 :                 (
    9719            4 :                     Lsn(0x40),
    9720            4 :                     KeyLogAtLsn(vec![(
    9721            4 :                         Lsn(0x40),
    9722            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9723            4 :                     )]),
    9724            4 :                 ),
    9725            4 :                 (
    9726            4 :                     Lsn(0x50),
    9727            4 :                     KeyLogAtLsn(vec![(
    9728            4 :                         Lsn(0x50),
    9729            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9730            4 :                     )]),
    9731            4 :                 ),
    9732            4 :                 (
    9733            4 :                     Lsn(0x60),
    9734            4 :                     KeyLogAtLsn(vec![(
    9735            4 :                         Lsn(0x60),
    9736            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9737            4 :                     )]),
    9738            4 :                 ),
    9739            4 :             ],
    9740            4 :             above_horizon: KeyLogAtLsn(vec![
    9741            4 :                 (
    9742            4 :                     Lsn(0x70),
    9743            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9744            4 :                 ),
    9745            4 :                 (
    9746            4 :                     Lsn(0x80),
    9747            4 :                     Value::Image(Bytes::copy_from_slice(
    9748            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9749            4 :                     )),
    9750            4 :                 ),
    9751            4 :                 (
    9752            4 :                     Lsn(0x90),
    9753            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9754            4 :                 ),
    9755            4 :             ]),
    9756            4 :         };
    9757            4 :         assert_eq!(res, expected_res);
    9758            4 : 
    9759            4 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9760            4 :         // the ancestor image in the test case.
    9761            4 : 
    9762            4 :         let history = vec![
    9763            4 :             (
    9764            4 :                 key,
    9765            4 :                 Lsn(0x20),
    9766            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9767            4 :             ),
    9768            4 :             (
    9769            4 :                 key,
    9770            4 :                 Lsn(0x30),
    9771            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9772            4 :             ),
    9773            4 :             (
    9774            4 :                 key,
    9775            4 :                 Lsn(0x40),
    9776            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9777            4 :             ),
    9778            4 :             (
    9779            4 :                 key,
    9780            4 :                 Lsn(0x70),
    9781            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9782            4 :             ),
    9783            4 :         ];
    9784            4 :         let res = tline
    9785            4 :             .generate_key_retention(
    9786            4 :                 key,
    9787            4 :                 &history,
    9788            4 :                 Lsn(0x60),
    9789            4 :                 &[],
    9790            4 :                 3,
    9791            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9792            4 :                 true,
    9793            4 :             )
    9794            4 :             .await
    9795            4 :             .unwrap();
    9796            4 :         let expected_res = KeyHistoryRetention {
    9797            4 :             below_horizon: vec![(
    9798            4 :                 Lsn(0x60),
    9799            4 :                 KeyLogAtLsn(vec![(
    9800            4 :                     Lsn(0x60),
    9801            4 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9802            4 :                 )]),
    9803            4 :             )],
    9804            4 :             above_horizon: KeyLogAtLsn(vec![(
    9805            4 :                 Lsn(0x70),
    9806            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9807            4 :             )]),
    9808            4 :         };
    9809            4 :         assert_eq!(res, expected_res);
    9810            4 : 
    9811            4 :         let history = vec![
    9812            4 :             (
    9813            4 :                 key,
    9814            4 :                 Lsn(0x20),
    9815            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9816            4 :             ),
    9817            4 :             (
    9818            4 :                 key,
    9819            4 :                 Lsn(0x40),
    9820            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9821            4 :             ),
    9822            4 :             (
    9823            4 :                 key,
    9824            4 :                 Lsn(0x60),
    9825            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9826            4 :             ),
    9827            4 :             (
    9828            4 :                 key,
    9829            4 :                 Lsn(0x70),
    9830            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9831            4 :             ),
    9832            4 :         ];
    9833            4 :         let res = tline
    9834            4 :             .generate_key_retention(
    9835            4 :                 key,
    9836            4 :                 &history,
    9837            4 :                 Lsn(0x60),
    9838            4 :                 &[Lsn(0x30)],
    9839            4 :                 3,
    9840            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9841            4 :                 true,
    9842            4 :             )
    9843            4 :             .await
    9844            4 :             .unwrap();
    9845            4 :         let expected_res = KeyHistoryRetention {
    9846            4 :             below_horizon: vec![
    9847            4 :                 (
    9848            4 :                     Lsn(0x30),
    9849            4 :                     KeyLogAtLsn(vec![(
    9850            4 :                         Lsn(0x20),
    9851            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9852            4 :                     )]),
    9853            4 :                 ),
    9854            4 :                 (
    9855            4 :                     Lsn(0x60),
    9856            4 :                     KeyLogAtLsn(vec![(
    9857            4 :                         Lsn(0x60),
    9858            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9859            4 :                     )]),
    9860            4 :                 ),
    9861            4 :             ],
    9862            4 :             above_horizon: KeyLogAtLsn(vec![(
    9863            4 :                 Lsn(0x70),
    9864            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9865            4 :             )]),
    9866            4 :         };
    9867            4 :         assert_eq!(res, expected_res);
    9868            4 : 
    9869            4 :         Ok(())
    9870            4 :     }
    9871              : 
    9872              :     #[cfg(feature = "testing")]
    9873              :     #[tokio::test]
    9874            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9875            4 :         let harness =
    9876            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9877            4 :         let (tenant, ctx) = harness.load().await;
    9878            4 : 
    9879         1036 :         fn get_key(id: u32) -> Key {
    9880         1036 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9881         1036 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9882         1036 :             key.field6 = id;
    9883         1036 :             key
    9884         1036 :         }
    9885            4 : 
    9886            4 :         let img_layer = (0..10)
    9887           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9888            4 :             .collect_vec();
    9889            4 : 
    9890            4 :         let delta1 = vec![
    9891            4 :             (
    9892            4 :                 get_key(1),
    9893            4 :                 Lsn(0x20),
    9894            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9895            4 :             ),
    9896            4 :             (
    9897            4 :                 get_key(2),
    9898            4 :                 Lsn(0x30),
    9899            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9900            4 :             ),
    9901            4 :             (
    9902            4 :                 get_key(3),
    9903            4 :                 Lsn(0x28),
    9904            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9905            4 :             ),
    9906            4 :             (
    9907            4 :                 get_key(3),
    9908            4 :                 Lsn(0x30),
    9909            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9910            4 :             ),
    9911            4 :             (
    9912            4 :                 get_key(3),
    9913            4 :                 Lsn(0x40),
    9914            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9915            4 :             ),
    9916            4 :         ];
    9917            4 :         let delta2 = vec![
    9918            4 :             (
    9919            4 :                 get_key(5),
    9920            4 :                 Lsn(0x20),
    9921            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9922            4 :             ),
    9923            4 :             (
    9924            4 :                 get_key(6),
    9925            4 :                 Lsn(0x20),
    9926            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9927            4 :             ),
    9928            4 :         ];
    9929            4 :         let delta3 = vec![
    9930            4 :             (
    9931            4 :                 get_key(8),
    9932            4 :                 Lsn(0x48),
    9933            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9934            4 :             ),
    9935            4 :             (
    9936            4 :                 get_key(9),
    9937            4 :                 Lsn(0x48),
    9938            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9939            4 :             ),
    9940            4 :         ];
    9941            4 : 
    9942            4 :         let tline = tenant
    9943            4 :             .create_test_timeline_with_layers(
    9944            4 :                 TIMELINE_ID,
    9945            4 :                 Lsn(0x10),
    9946            4 :                 DEFAULT_PG_VERSION,
    9947            4 :                 &ctx,
    9948            4 :                 Vec::new(), // in-memory layers
    9949            4 :                 vec![
    9950            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9951            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9952            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9953            4 :                 ], // delta layers
    9954            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9955            4 :                 Lsn(0x50),
    9956            4 :             )
    9957            4 :             .await?;
    9958            4 :         {
    9959            4 :             tline
    9960            4 :                 .applied_gc_cutoff_lsn
    9961            4 :                 .lock_for_write()
    9962            4 :                 .store_and_unlock(Lsn(0x30))
    9963            4 :                 .wait()
    9964            4 :                 .await;
    9965            4 :             // Update GC info
    9966            4 :             let mut guard = tline.gc_info.write().unwrap();
    9967            4 :             *guard = GcInfo {
    9968            4 :                 retain_lsns: vec![
    9969            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9970            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9971            4 :                 ],
    9972            4 :                 cutoffs: GcCutoffs {
    9973            4 :                     time: Lsn(0x30),
    9974            4 :                     space: Lsn(0x30),
    9975            4 :                 },
    9976            4 :                 leases: Default::default(),
    9977            4 :                 within_ancestor_pitr: false,
    9978            4 :             };
    9979            4 :         }
    9980            4 : 
    9981            4 :         let expected_result = [
    9982            4 :             Bytes::from_static(b"value 0@0x10"),
    9983            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9984            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9985            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9986            4 :             Bytes::from_static(b"value 4@0x10"),
    9987            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9988            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9989            4 :             Bytes::from_static(b"value 7@0x10"),
    9990            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9991            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9992            4 :         ];
    9993            4 : 
    9994            4 :         let expected_result_at_gc_horizon = [
    9995            4 :             Bytes::from_static(b"value 0@0x10"),
    9996            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9997            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9998            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9999            4 :             Bytes::from_static(b"value 4@0x10"),
   10000            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10001            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10002            4 :             Bytes::from_static(b"value 7@0x10"),
   10003            4 :             Bytes::from_static(b"value 8@0x10"),
   10004            4 :             Bytes::from_static(b"value 9@0x10"),
   10005            4 :         ];
   10006            4 : 
   10007            4 :         let expected_result_at_lsn_20 = [
   10008            4 :             Bytes::from_static(b"value 0@0x10"),
   10009            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10010            4 :             Bytes::from_static(b"value 2@0x10"),
   10011            4 :             Bytes::from_static(b"value 3@0x10"),
   10012            4 :             Bytes::from_static(b"value 4@0x10"),
   10013            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10014            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10015            4 :             Bytes::from_static(b"value 7@0x10"),
   10016            4 :             Bytes::from_static(b"value 8@0x10"),
   10017            4 :             Bytes::from_static(b"value 9@0x10"),
   10018            4 :         ];
   10019            4 : 
   10020            4 :         let expected_result_at_lsn_10 = [
   10021            4 :             Bytes::from_static(b"value 0@0x10"),
   10022            4 :             Bytes::from_static(b"value 1@0x10"),
   10023            4 :             Bytes::from_static(b"value 2@0x10"),
   10024            4 :             Bytes::from_static(b"value 3@0x10"),
   10025            4 :             Bytes::from_static(b"value 4@0x10"),
   10026            4 :             Bytes::from_static(b"value 5@0x10"),
   10027            4 :             Bytes::from_static(b"value 6@0x10"),
   10028            4 :             Bytes::from_static(b"value 7@0x10"),
   10029            4 :             Bytes::from_static(b"value 8@0x10"),
   10030            4 :             Bytes::from_static(b"value 9@0x10"),
   10031            4 :         ];
   10032            4 : 
   10033           24 :         let verify_result = || async {
   10034           24 :             let gc_horizon = {
   10035           24 :                 let gc_info = tline.gc_info.read().unwrap();
   10036           24 :                 gc_info.cutoffs.time
   10037            4 :             };
   10038          264 :             for idx in 0..10 {
   10039          240 :                 assert_eq!(
   10040          240 :                     tline
   10041          240 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10042          240 :                         .await
   10043          240 :                         .unwrap(),
   10044          240 :                     &expected_result[idx]
   10045            4 :                 );
   10046          240 :                 assert_eq!(
   10047          240 :                     tline
   10048          240 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10049          240 :                         .await
   10050          240 :                         .unwrap(),
   10051          240 :                     &expected_result_at_gc_horizon[idx]
   10052            4 :                 );
   10053          240 :                 assert_eq!(
   10054          240 :                     tline
   10055          240 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10056          240 :                         .await
   10057          240 :                         .unwrap(),
   10058          240 :                     &expected_result_at_lsn_20[idx]
   10059            4 :                 );
   10060          240 :                 assert_eq!(
   10061          240 :                     tline
   10062          240 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10063          240 :                         .await
   10064          240 :                         .unwrap(),
   10065          240 :                     &expected_result_at_lsn_10[idx]
   10066            4 :                 );
   10067            4 :             }
   10068           48 :         };
   10069            4 : 
   10070            4 :         verify_result().await;
   10071            4 : 
   10072            4 :         let cancel = CancellationToken::new();
   10073            4 :         let mut dryrun_flags = EnumSet::new();
   10074            4 :         dryrun_flags.insert(CompactFlags::DryRun);
   10075            4 : 
   10076            4 :         tline
   10077            4 :             .compact_with_gc(
   10078            4 :                 &cancel,
   10079            4 :                 CompactOptions {
   10080            4 :                     flags: dryrun_flags,
   10081            4 :                     ..Default::default()
   10082            4 :                 },
   10083            4 :                 &ctx,
   10084            4 :             )
   10085            4 :             .await
   10086            4 :             .unwrap();
   10087            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
   10088            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10089            4 :         verify_result().await;
   10090            4 : 
   10091            4 :         tline
   10092            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10093            4 :             .await
   10094            4 :             .unwrap();
   10095            4 :         verify_result().await;
   10096            4 : 
   10097            4 :         // compact again
   10098            4 :         tline
   10099            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10100            4 :             .await
   10101            4 :             .unwrap();
   10102            4 :         verify_result().await;
   10103            4 : 
   10104            4 :         // increase GC horizon and compact again
   10105            4 :         {
   10106            4 :             tline
   10107            4 :                 .applied_gc_cutoff_lsn
   10108            4 :                 .lock_for_write()
   10109            4 :                 .store_and_unlock(Lsn(0x38))
   10110            4 :                 .wait()
   10111            4 :                 .await;
   10112            4 :             // Update GC info
   10113            4 :             let mut guard = tline.gc_info.write().unwrap();
   10114            4 :             guard.cutoffs.time = Lsn(0x38);
   10115            4 :             guard.cutoffs.space = Lsn(0x38);
   10116            4 :         }
   10117            4 :         tline
   10118            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10119            4 :             .await
   10120            4 :             .unwrap();
   10121            4 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10122            4 : 
   10123            4 :         // not increasing the GC horizon and compact again
   10124            4 :         tline
   10125            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10126            4 :             .await
   10127            4 :             .unwrap();
   10128            4 :         verify_result().await;
   10129            4 : 
   10130            4 :         Ok(())
   10131            4 :     }
   10132              : 
   10133              :     #[cfg(feature = "testing")]
   10134              :     #[tokio::test]
   10135            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10136            4 :     {
   10137            4 :         let harness =
   10138            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10139            4 :                 .await?;
   10140            4 :         let (tenant, ctx) = harness.load().await;
   10141            4 : 
   10142          704 :         fn get_key(id: u32) -> Key {
   10143          704 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10144          704 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10145          704 :             key.field6 = id;
   10146          704 :             key
   10147          704 :         }
   10148            4 : 
   10149            4 :         let img_layer = (0..10)
   10150           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10151            4 :             .collect_vec();
   10152            4 : 
   10153            4 :         let delta1 = vec![
   10154            4 :             (
   10155            4 :                 get_key(1),
   10156            4 :                 Lsn(0x20),
   10157            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10158            4 :             ),
   10159            4 :             (
   10160            4 :                 get_key(1),
   10161            4 :                 Lsn(0x28),
   10162            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10163            4 :             ),
   10164            4 :         ];
   10165            4 :         let delta2 = vec![
   10166            4 :             (
   10167            4 :                 get_key(1),
   10168            4 :                 Lsn(0x30),
   10169            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10170            4 :             ),
   10171            4 :             (
   10172            4 :                 get_key(1),
   10173            4 :                 Lsn(0x38),
   10174            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10175            4 :             ),
   10176            4 :         ];
   10177            4 :         let delta3 = vec![
   10178            4 :             (
   10179            4 :                 get_key(8),
   10180            4 :                 Lsn(0x48),
   10181            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10182            4 :             ),
   10183            4 :             (
   10184            4 :                 get_key(9),
   10185            4 :                 Lsn(0x48),
   10186            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10187            4 :             ),
   10188            4 :         ];
   10189            4 : 
   10190            4 :         let tline = tenant
   10191            4 :             .create_test_timeline_with_layers(
   10192            4 :                 TIMELINE_ID,
   10193            4 :                 Lsn(0x10),
   10194            4 :                 DEFAULT_PG_VERSION,
   10195            4 :                 &ctx,
   10196            4 :                 Vec::new(), // in-memory layers
   10197            4 :                 vec![
   10198            4 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10199            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10200            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10201            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10202            4 :                 ], // delta layers
   10203            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10204            4 :                 Lsn(0x50),
   10205            4 :             )
   10206            4 :             .await?;
   10207            4 :         {
   10208            4 :             tline
   10209            4 :                 .applied_gc_cutoff_lsn
   10210            4 :                 .lock_for_write()
   10211            4 :                 .store_and_unlock(Lsn(0x30))
   10212            4 :                 .wait()
   10213            4 :                 .await;
   10214            4 :             // Update GC info
   10215            4 :             let mut guard = tline.gc_info.write().unwrap();
   10216            4 :             *guard = GcInfo {
   10217            4 :                 retain_lsns: vec![
   10218            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10219            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10220            4 :                 ],
   10221            4 :                 cutoffs: GcCutoffs {
   10222            4 :                     time: Lsn(0x30),
   10223            4 :                     space: Lsn(0x30),
   10224            4 :                 },
   10225            4 :                 leases: Default::default(),
   10226            4 :                 within_ancestor_pitr: false,
   10227            4 :             };
   10228            4 :         }
   10229            4 : 
   10230            4 :         let expected_result = [
   10231            4 :             Bytes::from_static(b"value 0@0x10"),
   10232            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10233            4 :             Bytes::from_static(b"value 2@0x10"),
   10234            4 :             Bytes::from_static(b"value 3@0x10"),
   10235            4 :             Bytes::from_static(b"value 4@0x10"),
   10236            4 :             Bytes::from_static(b"value 5@0x10"),
   10237            4 :             Bytes::from_static(b"value 6@0x10"),
   10238            4 :             Bytes::from_static(b"value 7@0x10"),
   10239            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10240            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10241            4 :         ];
   10242            4 : 
   10243            4 :         let expected_result_at_gc_horizon = [
   10244            4 :             Bytes::from_static(b"value 0@0x10"),
   10245            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10246            4 :             Bytes::from_static(b"value 2@0x10"),
   10247            4 :             Bytes::from_static(b"value 3@0x10"),
   10248            4 :             Bytes::from_static(b"value 4@0x10"),
   10249            4 :             Bytes::from_static(b"value 5@0x10"),
   10250            4 :             Bytes::from_static(b"value 6@0x10"),
   10251            4 :             Bytes::from_static(b"value 7@0x10"),
   10252            4 :             Bytes::from_static(b"value 8@0x10"),
   10253            4 :             Bytes::from_static(b"value 9@0x10"),
   10254            4 :         ];
   10255            4 : 
   10256            4 :         let expected_result_at_lsn_20 = [
   10257            4 :             Bytes::from_static(b"value 0@0x10"),
   10258            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10259            4 :             Bytes::from_static(b"value 2@0x10"),
   10260            4 :             Bytes::from_static(b"value 3@0x10"),
   10261            4 :             Bytes::from_static(b"value 4@0x10"),
   10262            4 :             Bytes::from_static(b"value 5@0x10"),
   10263            4 :             Bytes::from_static(b"value 6@0x10"),
   10264            4 :             Bytes::from_static(b"value 7@0x10"),
   10265            4 :             Bytes::from_static(b"value 8@0x10"),
   10266            4 :             Bytes::from_static(b"value 9@0x10"),
   10267            4 :         ];
   10268            4 : 
   10269            4 :         let expected_result_at_lsn_10 = [
   10270            4 :             Bytes::from_static(b"value 0@0x10"),
   10271            4 :             Bytes::from_static(b"value 1@0x10"),
   10272            4 :             Bytes::from_static(b"value 2@0x10"),
   10273            4 :             Bytes::from_static(b"value 3@0x10"),
   10274            4 :             Bytes::from_static(b"value 4@0x10"),
   10275            4 :             Bytes::from_static(b"value 5@0x10"),
   10276            4 :             Bytes::from_static(b"value 6@0x10"),
   10277            4 :             Bytes::from_static(b"value 7@0x10"),
   10278            4 :             Bytes::from_static(b"value 8@0x10"),
   10279            4 :             Bytes::from_static(b"value 9@0x10"),
   10280            4 :         ];
   10281            4 : 
   10282           16 :         let verify_result = || async {
   10283           16 :             let gc_horizon = {
   10284           16 :                 let gc_info = tline.gc_info.read().unwrap();
   10285           16 :                 gc_info.cutoffs.time
   10286            4 :             };
   10287          176 :             for idx in 0..10 {
   10288          160 :                 assert_eq!(
   10289          160 :                     tline
   10290          160 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10291          160 :                         .await
   10292          160 :                         .unwrap(),
   10293          160 :                     &expected_result[idx]
   10294            4 :                 );
   10295          160 :                 assert_eq!(
   10296          160 :                     tline
   10297          160 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10298          160 :                         .await
   10299          160 :                         .unwrap(),
   10300          160 :                     &expected_result_at_gc_horizon[idx]
   10301            4 :                 );
   10302          160 :                 assert_eq!(
   10303          160 :                     tline
   10304          160 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10305          160 :                         .await
   10306          160 :                         .unwrap(),
   10307          160 :                     &expected_result_at_lsn_20[idx]
   10308            4 :                 );
   10309          160 :                 assert_eq!(
   10310          160 :                     tline
   10311          160 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10312          160 :                         .await
   10313          160 :                         .unwrap(),
   10314          160 :                     &expected_result_at_lsn_10[idx]
   10315            4 :                 );
   10316            4 :             }
   10317           32 :         };
   10318            4 : 
   10319            4 :         verify_result().await;
   10320            4 : 
   10321            4 :         let cancel = CancellationToken::new();
   10322            4 :         let mut dryrun_flags = EnumSet::new();
   10323            4 :         dryrun_flags.insert(CompactFlags::DryRun);
   10324            4 : 
   10325            4 :         tline
   10326            4 :             .compact_with_gc(
   10327            4 :                 &cancel,
   10328            4 :                 CompactOptions {
   10329            4 :                     flags: dryrun_flags,
   10330            4 :                     ..Default::default()
   10331            4 :                 },
   10332            4 :                 &ctx,
   10333            4 :             )
   10334            4 :             .await
   10335            4 :             .unwrap();
   10336            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
   10337            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10338            4 :         verify_result().await;
   10339            4 : 
   10340            4 :         tline
   10341            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10342            4 :             .await
   10343            4 :             .unwrap();
   10344            4 :         verify_result().await;
   10345            4 : 
   10346            4 :         // compact again
   10347            4 :         tline
   10348            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10349            4 :             .await
   10350            4 :             .unwrap();
   10351            4 :         verify_result().await;
   10352            4 : 
   10353            4 :         Ok(())
   10354            4 :     }
   10355              : 
   10356              :     #[cfg(feature = "testing")]
   10357              :     #[tokio::test]
   10358            4 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10359            4 :         use models::CompactLsnRange;
   10360            4 : 
   10361            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10362            4 :         let (tenant, ctx) = harness.load().await;
   10363            4 : 
   10364          332 :         fn get_key(id: u32) -> Key {
   10365          332 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10366          332 :             key.field6 = id;
   10367          332 :             key
   10368          332 :         }
   10369            4 : 
   10370            4 :         let img_layer = (0..10)
   10371           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10372            4 :             .collect_vec();
   10373            4 : 
   10374            4 :         let delta1 = vec![
   10375            4 :             (
   10376            4 :                 get_key(1),
   10377            4 :                 Lsn(0x20),
   10378            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10379            4 :             ),
   10380            4 :             (
   10381            4 :                 get_key(2),
   10382            4 :                 Lsn(0x30),
   10383            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10384            4 :             ),
   10385            4 :             (
   10386            4 :                 get_key(3),
   10387            4 :                 Lsn(0x28),
   10388            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10389            4 :             ),
   10390            4 :             (
   10391            4 :                 get_key(3),
   10392            4 :                 Lsn(0x30),
   10393            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10394            4 :             ),
   10395            4 :             (
   10396            4 :                 get_key(3),
   10397            4 :                 Lsn(0x40),
   10398            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10399            4 :             ),
   10400            4 :         ];
   10401            4 :         let delta2 = vec![
   10402            4 :             (
   10403            4 :                 get_key(5),
   10404            4 :                 Lsn(0x20),
   10405            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10406            4 :             ),
   10407            4 :             (
   10408            4 :                 get_key(6),
   10409            4 :                 Lsn(0x20),
   10410            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10411            4 :             ),
   10412            4 :         ];
   10413            4 :         let delta3 = vec![
   10414            4 :             (
   10415            4 :                 get_key(8),
   10416            4 :                 Lsn(0x48),
   10417            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10418            4 :             ),
   10419            4 :             (
   10420            4 :                 get_key(9),
   10421            4 :                 Lsn(0x48),
   10422            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10423            4 :             ),
   10424            4 :         ];
   10425            4 : 
   10426            4 :         let parent_tline = tenant
   10427            4 :             .create_test_timeline_with_layers(
   10428            4 :                 TIMELINE_ID,
   10429            4 :                 Lsn(0x10),
   10430            4 :                 DEFAULT_PG_VERSION,
   10431            4 :                 &ctx,
   10432            4 :                 vec![],                       // in-memory layers
   10433            4 :                 vec![],                       // delta layers
   10434            4 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10435            4 :                 Lsn(0x18),
   10436            4 :             )
   10437            4 :             .await?;
   10438            4 : 
   10439            4 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10440            4 : 
   10441            4 :         let branch_tline = tenant
   10442            4 :             .branch_timeline_test_with_layers(
   10443            4 :                 &parent_tline,
   10444            4 :                 NEW_TIMELINE_ID,
   10445            4 :                 Some(Lsn(0x18)),
   10446            4 :                 &ctx,
   10447            4 :                 vec![
   10448            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10449            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10450            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10451            4 :                 ], // delta layers
   10452            4 :                 vec![], // image layers
   10453            4 :                 Lsn(0x50),
   10454            4 :             )
   10455            4 :             .await?;
   10456            4 : 
   10457            4 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10458            4 : 
   10459            4 :         {
   10460            4 :             parent_tline
   10461            4 :                 .applied_gc_cutoff_lsn
   10462            4 :                 .lock_for_write()
   10463            4 :                 .store_and_unlock(Lsn(0x10))
   10464            4 :                 .wait()
   10465            4 :                 .await;
   10466            4 :             // Update GC info
   10467            4 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10468            4 :             *guard = GcInfo {
   10469            4 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10470            4 :                 cutoffs: GcCutoffs {
   10471            4 :                     time: Lsn(0x10),
   10472            4 :                     space: Lsn(0x10),
   10473            4 :                 },
   10474            4 :                 leases: Default::default(),
   10475            4 :                 within_ancestor_pitr: false,
   10476            4 :             };
   10477            4 :         }
   10478            4 : 
   10479            4 :         {
   10480            4 :             branch_tline
   10481            4 :                 .applied_gc_cutoff_lsn
   10482            4 :                 .lock_for_write()
   10483            4 :                 .store_and_unlock(Lsn(0x50))
   10484            4 :                 .wait()
   10485            4 :                 .await;
   10486            4 :             // Update GC info
   10487            4 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10488            4 :             *guard = GcInfo {
   10489            4 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10490            4 :                 cutoffs: GcCutoffs {
   10491            4 :                     time: Lsn(0x50),
   10492            4 :                     space: Lsn(0x50),
   10493            4 :                 },
   10494            4 :                 leases: Default::default(),
   10495            4 :                 within_ancestor_pitr: false,
   10496            4 :             };
   10497            4 :         }
   10498            4 : 
   10499            4 :         let expected_result_at_gc_horizon = [
   10500            4 :             Bytes::from_static(b"value 0@0x10"),
   10501            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10502            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10503            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10504            4 :             Bytes::from_static(b"value 4@0x10"),
   10505            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10506            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10507            4 :             Bytes::from_static(b"value 7@0x10"),
   10508            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10509            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10510            4 :         ];
   10511            4 : 
   10512            4 :         let expected_result_at_lsn_40 = [
   10513            4 :             Bytes::from_static(b"value 0@0x10"),
   10514            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10515            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10516            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10517            4 :             Bytes::from_static(b"value 4@0x10"),
   10518            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10519            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10520            4 :             Bytes::from_static(b"value 7@0x10"),
   10521            4 :             Bytes::from_static(b"value 8@0x10"),
   10522            4 :             Bytes::from_static(b"value 9@0x10"),
   10523            4 :         ];
   10524            4 : 
   10525           12 :         let verify_result = || async {
   10526          132 :             for idx in 0..10 {
   10527          120 :                 assert_eq!(
   10528          120 :                     branch_tline
   10529          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10530          120 :                         .await
   10531          120 :                         .unwrap(),
   10532          120 :                     &expected_result_at_gc_horizon[idx]
   10533            4 :                 );
   10534          120 :                 assert_eq!(
   10535          120 :                     branch_tline
   10536          120 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10537          120 :                         .await
   10538          120 :                         .unwrap(),
   10539          120 :                     &expected_result_at_lsn_40[idx]
   10540            4 :                 );
   10541            4 :             }
   10542           24 :         };
   10543            4 : 
   10544            4 :         verify_result().await;
   10545            4 : 
   10546            4 :         let cancel = CancellationToken::new();
   10547            4 :         branch_tline
   10548            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10549            4 :             .await
   10550            4 :             .unwrap();
   10551            4 : 
   10552            4 :         verify_result().await;
   10553            4 : 
   10554            4 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10555            4 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10556            4 :         branch_tline
   10557            4 :             .compact_with_gc(
   10558            4 :                 &cancel,
   10559            4 :                 CompactOptions {
   10560            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10561            4 :                     ..Default::default()
   10562            4 :                 },
   10563            4 :                 &ctx,
   10564            4 :             )
   10565            4 :             .await
   10566            4 :             .unwrap();
   10567            4 : 
   10568            4 :         verify_result().await;
   10569            4 : 
   10570            4 :         Ok(())
   10571            4 :     }
   10572              : 
   10573              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10574              :     // Create an image arrangement where we have to read at different LSN ranges
   10575              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10576              :     // a delta layer. Like so:
   10577              :     //
   10578              :     //     A      B
   10579              :     // +----------------+ -> delta_layer
   10580              :     // |                |                           ^ lsn
   10581              :     // |       =========|-> nested_image_layer      |
   10582              :     // |       C        |                           |
   10583              :     // +----------------+                           |
   10584              :     // ======== -> baseline_image_layer             +-------> key
   10585              :     //
   10586              :     //
   10587              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10588              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10589              :     #[cfg(feature = "testing")]
   10590              :     #[tokio::test]
   10591            4 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10592            4 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10593            4 :         let (tenant, ctx) = harness.load().await;
   10594            4 : 
   10595            4 :         let will_init_keys = [2, 6];
   10596           88 :         fn get_key(id: u32) -> Key {
   10597           88 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10598           88 :             key.field6 = id;
   10599           88 :             key
   10600           88 :         }
   10601            4 : 
   10602            4 :         let mut expected_key_values = HashMap::new();
   10603            4 : 
   10604            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10605            4 :         let mut baseline_img_layer = Vec::new();
   10606           24 :         for i in 0..5 {
   10607           20 :             let key = get_key(i);
   10608           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10609           20 : 
   10610           20 :             let removed = expected_key_values.insert(key, value.clone());
   10611           20 :             assert!(removed.is_none());
   10612            4 : 
   10613           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10614            4 :         }
   10615            4 : 
   10616            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10617            4 :         let mut nested_img_layer = Vec::new();
   10618           24 :         for i in 5..10 {
   10619           20 :             let key = get_key(i);
   10620           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10621           20 : 
   10622           20 :             let removed = expected_key_values.insert(key, value.clone());
   10623           20 :             assert!(removed.is_none());
   10624            4 : 
   10625           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10626            4 :         }
   10627            4 : 
   10628            4 :         let mut delta_layer_spec = Vec::default();
   10629            4 :         let delta_layer_start_lsn = Lsn(0x20);
   10630            4 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10631            4 : 
   10632           44 :         for i in 0..10 {
   10633           40 :             let key = get_key(i);
   10634           40 :             let key_in_nested = nested_img_layer
   10635           40 :                 .iter()
   10636          160 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10637           40 :             let lsn = {
   10638           40 :                 if key_in_nested {
   10639           20 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10640            4 :                 } else {
   10641           20 :                     delta_layer_start_lsn
   10642            4 :                 }
   10643            4 :             };
   10644            4 : 
   10645           40 :             let will_init = will_init_keys.contains(&i);
   10646           40 :             if will_init {
   10647            8 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10648            8 : 
   10649            8 :                 expected_key_values.insert(key, "".to_string());
   10650           32 :             } else {
   10651           32 :                 let delta = format!("@{lsn}");
   10652           32 :                 delta_layer_spec.push((
   10653           32 :                     key,
   10654           32 :                     lsn,
   10655           32 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10656           32 :                 ));
   10657           32 : 
   10658           32 :                 expected_key_values
   10659           32 :                     .get_mut(&key)
   10660           32 :                     .expect("An image exists for each key")
   10661           32 :                     .push_str(delta.as_str());
   10662           32 :             }
   10663           40 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10664            4 :         }
   10665            4 : 
   10666            4 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10667            4 : 
   10668            4 :         assert!(
   10669            4 :             nested_image_layer_lsn > delta_layer_start_lsn
   10670            4 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10671            4 :         );
   10672            4 : 
   10673            4 :         let tline = tenant
   10674            4 :             .create_test_timeline_with_layers(
   10675            4 :                 TIMELINE_ID,
   10676            4 :                 baseline_image_layer_lsn,
   10677            4 :                 DEFAULT_PG_VERSION,
   10678            4 :                 &ctx,
   10679            4 :                 vec![], // in-memory layers
   10680            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10681            4 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10682            4 :                     delta_layer_spec,
   10683            4 :                 )], // delta layers
   10684            4 :                 vec![
   10685            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10686            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10687            4 :                 ], // image layers
   10688            4 :                 delta_layer_end_lsn,
   10689            4 :             )
   10690            4 :             .await?;
   10691            4 : 
   10692            4 :         let query = VersionedKeySpaceQuery::uniform(
   10693            4 :             KeySpace::single(get_key(0)..get_key(10)),
   10694            4 :             delta_layer_end_lsn,
   10695            4 :         );
   10696            4 : 
   10697            4 :         let results = tline
   10698            4 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   10699            4 :             .await
   10700            4 :             .expect("No vectored errors");
   10701           44 :         for (key, res) in results {
   10702           40 :             let value = res.expect("No key errors");
   10703           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10704           40 :             assert_eq!(value, Bytes::from(expected_value));
   10705            4 :         }
   10706            4 : 
   10707            4 :         Ok(())
   10708            4 :     }
   10709              : 
   10710              :     #[cfg(feature = "testing")]
   10711              :     #[tokio::test]
   10712            4 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   10713            4 :         let harness =
   10714            4 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   10715            4 :         let (tenant, ctx) = harness.load().await;
   10716            4 : 
   10717            4 :         let will_init_keys = [2, 6];
   10718          128 :         fn get_key(id: u32) -> Key {
   10719          128 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10720          128 :             key.field6 = id;
   10721          128 :             key
   10722          128 :         }
   10723            4 : 
   10724            4 :         let mut expected_key_values = HashMap::new();
   10725            4 : 
   10726            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10727            4 :         let mut baseline_img_layer = Vec::new();
   10728           24 :         for i in 0..5 {
   10729           20 :             let key = get_key(i);
   10730           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10731           20 : 
   10732           20 :             let removed = expected_key_values.insert(key, value.clone());
   10733           20 :             assert!(removed.is_none());
   10734            4 : 
   10735           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10736            4 :         }
   10737            4 : 
   10738            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10739            4 :         let mut nested_img_layer = Vec::new();
   10740           24 :         for i in 5..10 {
   10741           20 :             let key = get_key(i);
   10742           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10743           20 : 
   10744           20 :             let removed = expected_key_values.insert(key, value.clone());
   10745           20 :             assert!(removed.is_none());
   10746            4 : 
   10747           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10748            4 :         }
   10749            4 : 
   10750            4 :         let frozen_layer = {
   10751            4 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   10752            4 :             let mut data = Vec::new();
   10753           44 :             for i in 0..10 {
   10754           40 :                 let key = get_key(i);
   10755           40 :                 let key_in_nested = nested_img_layer
   10756           40 :                     .iter()
   10757          160 :                     .any(|(key_with_img, _)| *key_with_img == key);
   10758           40 :                 let lsn = {
   10759           40 :                     if key_in_nested {
   10760           20 :                         Lsn(nested_image_layer_lsn.0 + 5)
   10761            4 :                     } else {
   10762           20 :                         lsn_range.start
   10763            4 :                     }
   10764            4 :                 };
   10765            4 : 
   10766           40 :                 let will_init = will_init_keys.contains(&i);
   10767           40 :                 if will_init {
   10768            8 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10769            8 : 
   10770            8 :                     expected_key_values.insert(key, "".to_string());
   10771           32 :                 } else {
   10772           32 :                     let delta = format!("@{lsn}");
   10773           32 :                     data.push((
   10774           32 :                         key,
   10775           32 :                         lsn,
   10776           32 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10777           32 :                     ));
   10778           32 : 
   10779           32 :                     expected_key_values
   10780           32 :                         .get_mut(&key)
   10781           32 :                         .expect("An image exists for each key")
   10782           32 :                         .push_str(delta.as_str());
   10783           32 :                 }
   10784            4 :             }
   10785            4 : 
   10786            4 :             InMemoryLayerTestDesc {
   10787            4 :                 lsn_range,
   10788            4 :                 is_open: false,
   10789            4 :                 data,
   10790            4 :             }
   10791            4 :         };
   10792            4 : 
   10793            4 :         let (open_layer, last_record_lsn) = {
   10794            4 :             let start_lsn = Lsn(0x70);
   10795            4 :             let mut data = Vec::new();
   10796            4 :             let mut end_lsn = Lsn(0);
   10797           44 :             for i in 0..10 {
   10798           40 :                 let key = get_key(i);
   10799           40 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   10800           40 :                 let delta = format!("@{lsn}");
   10801           40 :                 data.push((
   10802           40 :                     key,
   10803           40 :                     lsn,
   10804           40 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10805           40 :                 ));
   10806           40 : 
   10807           40 :                 expected_key_values
   10808           40 :                     .get_mut(&key)
   10809           40 :                     .expect("An image exists for each key")
   10810           40 :                     .push_str(delta.as_str());
   10811           40 : 
   10812           40 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   10813           40 :             }
   10814            4 : 
   10815            4 :             (
   10816            4 :                 InMemoryLayerTestDesc {
   10817            4 :                     lsn_range: start_lsn..Lsn::MAX,
   10818            4 :                     is_open: true,
   10819            4 :                     data,
   10820            4 :                 },
   10821            4 :                 end_lsn,
   10822            4 :             )
   10823            4 :         };
   10824            4 : 
   10825            4 :         assert!(
   10826            4 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   10827            4 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   10828            4 :         );
   10829            4 : 
   10830            4 :         let tline = tenant
   10831            4 :             .create_test_timeline_with_layers(
   10832            4 :                 TIMELINE_ID,
   10833            4 :                 baseline_image_layer_lsn,
   10834            4 :                 DEFAULT_PG_VERSION,
   10835            4 :                 &ctx,
   10836            4 :                 vec![open_layer, frozen_layer], // in-memory layers
   10837            4 :                 Vec::new(),                     // delta layers
   10838            4 :                 vec![
   10839            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10840            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10841            4 :                 ], // image layers
   10842            4 :                 last_record_lsn,
   10843            4 :             )
   10844            4 :             .await?;
   10845            4 : 
   10846            4 :         let query = VersionedKeySpaceQuery::uniform(
   10847            4 :             KeySpace::single(get_key(0)..get_key(10)),
   10848            4 :             last_record_lsn,
   10849            4 :         );
   10850            4 : 
   10851            4 :         let results = tline
   10852            4 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   10853            4 :             .await
   10854            4 :             .expect("No vectored errors");
   10855           44 :         for (key, res) in results {
   10856           40 :             let value = res.expect("No key errors");
   10857           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10858           40 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   10859            4 : 
   10860           40 :             tracing::info!("key={key} value={expected_value}");
   10861            4 :         }
   10862            4 : 
   10863            4 :         Ok(())
   10864            4 :     }
   10865              : 
   10866              :     // A randomized read path test. Generates a layer map according to a deterministic
   10867              :     // specification. Fills the (key, LSN) space in random manner and then performs
   10868              :     // random scattered queries validating the results against in-memory storage.
   10869              :     //
   10870              :     // See this internal Notion page for a diagram of the layer map:
   10871              :     // https://www.notion.so/neondatabase/Read-Path-Unit-Testing-Fuzzing-1d1f189e0047806c8e5cd37781b0a350?pvs=4
   10872              :     //
   10873              :     // A fuzzing mode is also supported. In this mode, the test will use a random
   10874              :     // seed instead of a hardcoded one. Use it in conjunction with `cargo stress`
   10875              :     // to run multiple instances in parallel:
   10876              :     //
   10877              :     // $ RUST_BACKTRACE=1 RUST_LOG=INFO \
   10878              :     //   cargo stress --package=pageserver --features=testing,fuzz-read-path --release -- test_read_path
   10879              :     #[cfg(feature = "testing")]
   10880              :     #[tokio::test]
   10881            4 :     async fn test_read_path() -> anyhow::Result<()> {
   10882            4 :         use rand::seq::SliceRandom;
   10883            4 : 
   10884            4 :         let seed = if cfg!(feature = "fuzz-read-path") {
   10885            4 :             let seed: u64 = thread_rng().r#gen();
   10886            0 :             seed
   10887            4 :         } else {
   10888            4 :             // Use a hard-coded seed when not in fuzzing mode.
   10889            4 :             // Note that with the current approach results are not reproducible
   10890            4 :             // accross platforms and Rust releases.
   10891            4 :             const SEED: u64 = 0;
   10892            4 :             SEED
   10893            4 :         };
   10894            4 : 
   10895            4 :         let mut random = StdRng::seed_from_u64(seed);
   10896            4 : 
   10897            4 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   10898            4 :             const QUERIES: u64 = 5000;
   10899            4 :             let will_init_chance: u8 = random.gen_range(0..=10);
   10900            0 :             let gap_chance: u8 = random.gen_range(0..=50);
   10901            0 : 
   10902            0 :             (QUERIES, will_init_chance, gap_chance)
   10903            4 :         } else {
   10904            4 :             const QUERIES: u64 = 1000;
   10905            4 :             const WILL_INIT_CHANCE: u8 = 1;
   10906            4 :             const GAP_CHANCE: u8 = 5;
   10907            4 : 
   10908            4 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   10909            4 :         };
   10910            4 : 
   10911            4 :         let harness = TenantHarness::create("test_read_path").await?;
   10912            4 :         let (tenant, ctx) = harness.load().await;
   10913            4 : 
   10914            4 :         tracing::info!("Using random seed: {seed}");
   10915            4 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   10916            4 : 
   10917            4 :         // Define the layer map shape. Note that this part is not randomized.
   10918            4 : 
   10919            4 :         const KEY_DIMENSION_SIZE: u32 = 99;
   10920            4 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10921            4 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   10922            4 :         let total_key_range = start_key..end_key;
   10923            4 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   10924            4 :         let total_start_lsn = Lsn(104);
   10925            4 :         let last_record_lsn = Lsn(504);
   10926            4 : 
   10927            4 :         assert!(total_key_range_size % 3 == 0);
   10928            4 : 
   10929            4 :         let in_memory_layers_shape = vec![
   10930            4 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   10931            4 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   10932            4 :         ];
   10933            4 : 
   10934            4 :         let delta_layers_shape = vec![
   10935            4 :             (
   10936            4 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   10937            4 :                 Lsn(200)..Lsn(304),
   10938            4 :             ),
   10939            4 :             (
   10940            4 :                 (start_key.add((total_key_range_size / 3) as u32))
   10941            4 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   10942            4 :                 Lsn(200)..Lsn(304),
   10943            4 :             ),
   10944            4 :             (
   10945            4 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   10946            4 :                     ..(start_key.add(total_key_range_size as u32)),
   10947            4 :                 Lsn(200)..Lsn(304),
   10948            4 :             ),
   10949            4 :         ];
   10950            4 : 
   10951            4 :         let image_layers_shape = vec![
   10952            4 :             (
   10953            4 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   10954            4 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   10955            4 :                 Lsn(456),
   10956            4 :             ),
   10957            4 :             (
   10958            4 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   10959            4 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   10960            4 :                 Lsn(256),
   10961            4 :             ),
   10962            4 :             (total_key_range.clone(), total_start_lsn),
   10963            4 :         ];
   10964            4 : 
   10965            4 :         let specification = TestTimelineSpecification {
   10966            4 :             start_lsn: total_start_lsn,
   10967            4 :             last_record_lsn,
   10968            4 :             in_memory_layers_shape,
   10969            4 :             delta_layers_shape,
   10970            4 :             image_layers_shape,
   10971            4 :             gap_chance,
   10972            4 :             will_init_chance,
   10973            4 :         };
   10974            4 : 
   10975            4 :         // Create and randomly fill in the layers according to the specification
   10976            4 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   10977            4 :             &tenant,
   10978            4 :             TIMELINE_ID,
   10979            4 :             DEFAULT_PG_VERSION,
   10980            4 :             specification,
   10981            4 :             &mut random,
   10982            4 :             &ctx,
   10983            4 :         )
   10984            4 :         .await?;
   10985            4 : 
   10986            4 :         // Now generate queries based on the interesting lsns that we've collected.
   10987            4 :         //
   10988            4 :         // While there's still room in the query, pick and interesting LSN and a random
   10989            4 :         // key. Then roll the dice to see if the next key should also be included in
   10990            4 :         // the query. When the roll fails, break the "batch" and pick another point in the
   10991            4 :         // (key, LSN) space.
   10992            4 : 
   10993            4 :         const PICK_NEXT_CHANCE: u8 = 50;
   10994            4 :         for _ in 0..queries {
   10995         4000 :             let query = {
   10996         4000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   10997         4000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   10998            4 : 
   10999        90144 :                 while used_keys.len() < Timeline::MAX_GET_VECTORED_KEYS as usize {
   11000        86144 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11001        86144 :                     let mut selected_key = start_key.add(random.gen_range(0..KEY_DIMENSION_SIZE));
   11002            4 : 
   11003       150456 :                     while used_keys.len() < Timeline::MAX_GET_VECTORED_KEYS as usize {
   11004       148372 :                         if used_keys.contains(&selected_key)
   11005       128616 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11006            4 :                         {
   11007        20372 :                             break;
   11008       128000 :                         }
   11009       128000 : 
   11010       128000 :                         keyspaces_at_lsn
   11011       128000 :                             .entry(*selected_lsn)
   11012       128000 :                             .or_default()
   11013       128000 :                             .add_key(selected_key);
   11014       128000 :                         used_keys.insert(selected_key);
   11015       128000 : 
   11016       128000 :                         let pick_next = random.gen_range(0..=100) <= PICK_NEXT_CHANCE;
   11017       128000 :                         if pick_next {
   11018        64312 :                             selected_key = selected_key.next();
   11019        64312 :                         } else {
   11020        63688 :                             break;
   11021            4 :                         }
   11022            4 :                     }
   11023            4 :                 }
   11024            4 : 
   11025         4000 :                 VersionedKeySpaceQuery::scattered(
   11026         4000 :                     keyspaces_at_lsn
   11027         4000 :                         .into_iter()
   11028        47668 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11029         4000 :                         .collect(),
   11030         4000 :                 )
   11031            4 :             };
   11032            4 : 
   11033            4 :             // Run the query and validate the results
   11034            4 : 
   11035         4000 :             let results = tline
   11036         4000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11037         4000 :                 .await;
   11038            4 : 
   11039         4000 :             let blobs = match results {
   11040         4000 :                 Ok(ok) => ok,
   11041            4 :                 Err(err) => {
   11042            0 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11043            4 :                 }
   11044            4 :             };
   11045            4 : 
   11046       128000 :             for (key, key_res) in blobs.into_iter() {
   11047       128000 :                 match key_res {
   11048       128000 :                     Ok(blob) => {
   11049       128000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11050       128000 :                         let expected = storage.get(key, requested_at_lsn);
   11051       128000 : 
   11052       128000 :                         if blob != expected {
   11053            4 :                             tracing::error!(
   11054            4 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11055            4 :                             );
   11056       128000 :                         }
   11057            4 : 
   11058       128000 :                         assert_eq!(blob, expected);
   11059            4 :                     }
   11060            4 :                     Err(err) => {
   11061            0 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11062            0 : 
   11063            0 :                         panic!(
   11064            0 :                             "seed={seed} Error returned for {key}@{requested_at_lsn} from query {query}: {err}"
   11065            0 :                         );
   11066            4 :                     }
   11067            4 :                 }
   11068            4 :             }
   11069            4 :         }
   11070            4 : 
   11071            4 :         Ok(())
   11072            4 :     }
   11073              : 
   11074          428 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11075          428 :         (
   11076          428 :             k1.is_delta,
   11077          428 :             k1.key_range.start,
   11078          428 :             k1.key_range.end,
   11079          428 :             k1.lsn_range.start,
   11080          428 :             k1.lsn_range.end,
   11081          428 :         )
   11082          428 :             .cmp(&(
   11083          428 :                 k2.is_delta,
   11084          428 :                 k2.key_range.start,
   11085          428 :                 k2.key_range.end,
   11086          428 :                 k2.lsn_range.start,
   11087          428 :                 k2.lsn_range.end,
   11088          428 :             ))
   11089          428 :     }
   11090              : 
   11091           48 :     async fn inspect_and_sort(
   11092           48 :         tline: &Arc<Timeline>,
   11093           48 :         filter: Option<std::ops::Range<Key>>,
   11094           48 :     ) -> Vec<PersistentLayerKey> {
   11095           48 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11096           48 :         if let Some(filter) = filter {
   11097          216 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11098           44 :         }
   11099           48 :         all_layers.sort_by(sort_layer_key);
   11100           48 :         all_layers
   11101           48 :     }
   11102              : 
   11103              :     #[cfg(feature = "testing")]
   11104           44 :     fn check_layer_map_key_eq(
   11105           44 :         mut left: Vec<PersistentLayerKey>,
   11106           44 :         mut right: Vec<PersistentLayerKey>,
   11107           44 :     ) {
   11108           44 :         left.sort_by(sort_layer_key);
   11109           44 :         right.sort_by(sort_layer_key);
   11110           44 :         if left != right {
   11111            0 :             eprintln!("---LEFT---");
   11112            0 :             for left in left.iter() {
   11113            0 :                 eprintln!("{}", left);
   11114            0 :             }
   11115            0 :             eprintln!("---RIGHT---");
   11116            0 :             for right in right.iter() {
   11117            0 :                 eprintln!("{}", right);
   11118            0 :             }
   11119            0 :             assert_eq!(left, right);
   11120           44 :         }
   11121           44 :     }
   11122              : 
   11123              :     #[cfg(feature = "testing")]
   11124              :     #[tokio::test]
   11125            4 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11126            4 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11127            4 :         let (tenant, ctx) = harness.load().await;
   11128            4 : 
   11129          364 :         fn get_key(id: u32) -> Key {
   11130          364 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11131          364 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11132          364 :             key.field6 = id;
   11133          364 :             key
   11134          364 :         }
   11135            4 : 
   11136            4 :         // img layer at 0x10
   11137            4 :         let img_layer = (0..10)
   11138           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11139            4 :             .collect_vec();
   11140            4 : 
   11141            4 :         let delta1 = vec![
   11142            4 :             (
   11143            4 :                 get_key(1),
   11144            4 :                 Lsn(0x20),
   11145            4 :                 Value::Image(Bytes::from("value 1@0x20")),
   11146            4 :             ),
   11147            4 :             (
   11148            4 :                 get_key(2),
   11149            4 :                 Lsn(0x30),
   11150            4 :                 Value::Image(Bytes::from("value 2@0x30")),
   11151            4 :             ),
   11152            4 :             (
   11153            4 :                 get_key(3),
   11154            4 :                 Lsn(0x40),
   11155            4 :                 Value::Image(Bytes::from("value 3@0x40")),
   11156            4 :             ),
   11157            4 :         ];
   11158            4 :         let delta2 = vec![
   11159            4 :             (
   11160            4 :                 get_key(5),
   11161            4 :                 Lsn(0x20),
   11162            4 :                 Value::Image(Bytes::from("value 5@0x20")),
   11163            4 :             ),
   11164            4 :             (
   11165            4 :                 get_key(6),
   11166            4 :                 Lsn(0x20),
   11167            4 :                 Value::Image(Bytes::from("value 6@0x20")),
   11168            4 :             ),
   11169            4 :         ];
   11170            4 :         let delta3 = vec![
   11171            4 :             (
   11172            4 :                 get_key(8),
   11173            4 :                 Lsn(0x48),
   11174            4 :                 Value::Image(Bytes::from("value 8@0x48")),
   11175            4 :             ),
   11176            4 :             (
   11177            4 :                 get_key(9),
   11178            4 :                 Lsn(0x48),
   11179            4 :                 Value::Image(Bytes::from("value 9@0x48")),
   11180            4 :             ),
   11181            4 :         ];
   11182            4 : 
   11183            4 :         let tline = tenant
   11184            4 :             .create_test_timeline_with_layers(
   11185            4 :                 TIMELINE_ID,
   11186            4 :                 Lsn(0x10),
   11187            4 :                 DEFAULT_PG_VERSION,
   11188            4 :                 &ctx,
   11189            4 :                 vec![], // in-memory layers
   11190            4 :                 vec![
   11191            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11192            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11193            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11194            4 :                 ], // delta layers
   11195            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11196            4 :                 Lsn(0x50),
   11197            4 :             )
   11198            4 :             .await?;
   11199            4 : 
   11200            4 :         {
   11201            4 :             tline
   11202            4 :                 .applied_gc_cutoff_lsn
   11203            4 :                 .lock_for_write()
   11204            4 :                 .store_and_unlock(Lsn(0x30))
   11205            4 :                 .wait()
   11206            4 :                 .await;
   11207            4 :             // Update GC info
   11208            4 :             let mut guard = tline.gc_info.write().unwrap();
   11209            4 :             *guard = GcInfo {
   11210            4 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11211            4 :                 cutoffs: GcCutoffs {
   11212            4 :                     time: Lsn(0x30),
   11213            4 :                     space: Lsn(0x30),
   11214            4 :                 },
   11215            4 :                 leases: Default::default(),
   11216            4 :                 within_ancestor_pitr: false,
   11217            4 :             };
   11218            4 :         }
   11219            4 : 
   11220            4 :         let cancel = CancellationToken::new();
   11221            4 : 
   11222            4 :         // Do a partial compaction on key range 0..2
   11223            4 :         tline
   11224            4 :             .compact_with_gc(
   11225            4 :                 &cancel,
   11226            4 :                 CompactOptions {
   11227            4 :                     flags: EnumSet::new(),
   11228            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11229            4 :                     ..Default::default()
   11230            4 :                 },
   11231            4 :                 &ctx,
   11232            4 :             )
   11233            4 :             .await
   11234            4 :             .unwrap();
   11235            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11236            4 :         check_layer_map_key_eq(
   11237            4 :             all_layers,
   11238            4 :             vec![
   11239            4 :                 // newly-generated image layer for the partial compaction range 0-2
   11240            4 :                 PersistentLayerKey {
   11241            4 :                     key_range: get_key(0)..get_key(2),
   11242            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11243            4 :                     is_delta: false,
   11244            4 :                 },
   11245            4 :                 PersistentLayerKey {
   11246            4 :                     key_range: get_key(0)..get_key(10),
   11247            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11248            4 :                     is_delta: false,
   11249            4 :                 },
   11250            4 :                 // delta1 is split and the second part is rewritten
   11251            4 :                 PersistentLayerKey {
   11252            4 :                     key_range: get_key(2)..get_key(4),
   11253            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11254            4 :                     is_delta: true,
   11255            4 :                 },
   11256            4 :                 PersistentLayerKey {
   11257            4 :                     key_range: get_key(5)..get_key(7),
   11258            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11259            4 :                     is_delta: true,
   11260            4 :                 },
   11261            4 :                 PersistentLayerKey {
   11262            4 :                     key_range: get_key(8)..get_key(10),
   11263            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11264            4 :                     is_delta: true,
   11265            4 :                 },
   11266            4 :             ],
   11267            4 :         );
   11268            4 : 
   11269            4 :         // Do a partial compaction on key range 2..4
   11270            4 :         tline
   11271            4 :             .compact_with_gc(
   11272            4 :                 &cancel,
   11273            4 :                 CompactOptions {
   11274            4 :                     flags: EnumSet::new(),
   11275            4 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11276            4 :                     ..Default::default()
   11277            4 :                 },
   11278            4 :                 &ctx,
   11279            4 :             )
   11280            4 :             .await
   11281            4 :             .unwrap();
   11282            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11283            4 :         check_layer_map_key_eq(
   11284            4 :             all_layers,
   11285            4 :             vec![
   11286            4 :                 PersistentLayerKey {
   11287            4 :                     key_range: get_key(0)..get_key(2),
   11288            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11289            4 :                     is_delta: false,
   11290            4 :                 },
   11291            4 :                 PersistentLayerKey {
   11292            4 :                     key_range: get_key(0)..get_key(10),
   11293            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11294            4 :                     is_delta: false,
   11295            4 :                 },
   11296            4 :                 // image layer generated for the compaction range 2-4
   11297            4 :                 PersistentLayerKey {
   11298            4 :                     key_range: get_key(2)..get_key(4),
   11299            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11300            4 :                     is_delta: false,
   11301            4 :                 },
   11302            4 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11303            4 :                 PersistentLayerKey {
   11304            4 :                     key_range: get_key(2)..get_key(4),
   11305            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11306            4 :                     is_delta: true,
   11307            4 :                 },
   11308            4 :                 PersistentLayerKey {
   11309            4 :                     key_range: get_key(5)..get_key(7),
   11310            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11311            4 :                     is_delta: true,
   11312            4 :                 },
   11313            4 :                 PersistentLayerKey {
   11314            4 :                     key_range: get_key(8)..get_key(10),
   11315            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11316            4 :                     is_delta: true,
   11317            4 :                 },
   11318            4 :             ],
   11319            4 :         );
   11320            4 : 
   11321            4 :         // Do a partial compaction on key range 4..9
   11322            4 :         tline
   11323            4 :             .compact_with_gc(
   11324            4 :                 &cancel,
   11325            4 :                 CompactOptions {
   11326            4 :                     flags: EnumSet::new(),
   11327            4 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11328            4 :                     ..Default::default()
   11329            4 :                 },
   11330            4 :                 &ctx,
   11331            4 :             )
   11332            4 :             .await
   11333            4 :             .unwrap();
   11334            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11335            4 :         check_layer_map_key_eq(
   11336            4 :             all_layers,
   11337            4 :             vec![
   11338            4 :                 PersistentLayerKey {
   11339            4 :                     key_range: get_key(0)..get_key(2),
   11340            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11341            4 :                     is_delta: false,
   11342            4 :                 },
   11343            4 :                 PersistentLayerKey {
   11344            4 :                     key_range: get_key(0)..get_key(10),
   11345            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11346            4 :                     is_delta: false,
   11347            4 :                 },
   11348            4 :                 PersistentLayerKey {
   11349            4 :                     key_range: get_key(2)..get_key(4),
   11350            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11351            4 :                     is_delta: false,
   11352            4 :                 },
   11353            4 :                 PersistentLayerKey {
   11354            4 :                     key_range: get_key(2)..get_key(4),
   11355            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11356            4 :                     is_delta: true,
   11357            4 :                 },
   11358            4 :                 // image layer generated for this compaction range
   11359            4 :                 PersistentLayerKey {
   11360            4 :                     key_range: get_key(4)..get_key(9),
   11361            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11362            4 :                     is_delta: false,
   11363            4 :                 },
   11364            4 :                 PersistentLayerKey {
   11365            4 :                     key_range: get_key(8)..get_key(10),
   11366            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11367            4 :                     is_delta: true,
   11368            4 :                 },
   11369            4 :             ],
   11370            4 :         );
   11371            4 : 
   11372            4 :         // Do a partial compaction on key range 9..10
   11373            4 :         tline
   11374            4 :             .compact_with_gc(
   11375            4 :                 &cancel,
   11376            4 :                 CompactOptions {
   11377            4 :                     flags: EnumSet::new(),
   11378            4 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11379            4 :                     ..Default::default()
   11380            4 :                 },
   11381            4 :                 &ctx,
   11382            4 :             )
   11383            4 :             .await
   11384            4 :             .unwrap();
   11385            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11386            4 :         check_layer_map_key_eq(
   11387            4 :             all_layers,
   11388            4 :             vec![
   11389            4 :                 PersistentLayerKey {
   11390            4 :                     key_range: get_key(0)..get_key(2),
   11391            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11392            4 :                     is_delta: false,
   11393            4 :                 },
   11394            4 :                 PersistentLayerKey {
   11395            4 :                     key_range: get_key(0)..get_key(10),
   11396            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11397            4 :                     is_delta: false,
   11398            4 :                 },
   11399            4 :                 PersistentLayerKey {
   11400            4 :                     key_range: get_key(2)..get_key(4),
   11401            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11402            4 :                     is_delta: false,
   11403            4 :                 },
   11404            4 :                 PersistentLayerKey {
   11405            4 :                     key_range: get_key(2)..get_key(4),
   11406            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11407            4 :                     is_delta: true,
   11408            4 :                 },
   11409            4 :                 PersistentLayerKey {
   11410            4 :                     key_range: get_key(4)..get_key(9),
   11411            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11412            4 :                     is_delta: false,
   11413            4 :                 },
   11414            4 :                 // image layer generated for the compaction range
   11415            4 :                 PersistentLayerKey {
   11416            4 :                     key_range: get_key(9)..get_key(10),
   11417            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11418            4 :                     is_delta: false,
   11419            4 :                 },
   11420            4 :                 PersistentLayerKey {
   11421            4 :                     key_range: get_key(8)..get_key(10),
   11422            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11423            4 :                     is_delta: true,
   11424            4 :                 },
   11425            4 :             ],
   11426            4 :         );
   11427            4 : 
   11428            4 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11429            4 :         tline
   11430            4 :             .compact_with_gc(
   11431            4 :                 &cancel,
   11432            4 :                 CompactOptions {
   11433            4 :                     flags: EnumSet::new(),
   11434            4 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11435            4 :                     ..Default::default()
   11436            4 :                 },
   11437            4 :                 &ctx,
   11438            4 :             )
   11439            4 :             .await
   11440            4 :             .unwrap();
   11441            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11442            4 :         check_layer_map_key_eq(
   11443            4 :             all_layers,
   11444            4 :             vec![
   11445            4 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11446            4 :                 PersistentLayerKey {
   11447            4 :                     key_range: get_key(0)..get_key(10),
   11448            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11449            4 :                     is_delta: false,
   11450            4 :                 },
   11451            4 :                 PersistentLayerKey {
   11452            4 :                     key_range: get_key(2)..get_key(4),
   11453            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11454            4 :                     is_delta: true,
   11455            4 :                 },
   11456            4 :                 PersistentLayerKey {
   11457            4 :                     key_range: get_key(8)..get_key(10),
   11458            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11459            4 :                     is_delta: true,
   11460            4 :                 },
   11461            4 :             ],
   11462            4 :         );
   11463            4 :         Ok(())
   11464            4 :     }
   11465              : 
   11466              :     #[cfg(feature = "testing")]
   11467              :     #[tokio::test]
   11468            4 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11469            4 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11470            4 :             .await
   11471            4 :             .unwrap();
   11472            4 :         let (tenant, ctx) = harness.load().await;
   11473            4 :         let tline_parent = tenant
   11474            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11475            4 :             .await
   11476            4 :             .unwrap();
   11477            4 :         let tline_child = tenant
   11478            4 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11479            4 :             .await
   11480            4 :             .unwrap();
   11481            4 :         {
   11482            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11483            4 :             assert_eq!(
   11484            4 :                 gc_info_parent.retain_lsns,
   11485            4 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11486            4 :             );
   11487            4 :         }
   11488            4 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11489            4 :         tline_child
   11490            4 :             .remote_client
   11491            4 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11492            4 :             .unwrap();
   11493            4 :         tline_child.remote_client.wait_completion().await.unwrap();
   11494            4 :         offload_timeline(&tenant, &tline_child)
   11495            4 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11496            4 :             .await.unwrap();
   11497            4 :         let child_timeline_id = tline_child.timeline_id;
   11498            4 :         Arc::try_unwrap(tline_child).unwrap();
   11499            4 : 
   11500            4 :         {
   11501            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11502            4 :             assert_eq!(
   11503            4 :                 gc_info_parent.retain_lsns,
   11504            4 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11505            4 :             );
   11506            4 :         }
   11507            4 : 
   11508            4 :         tenant
   11509            4 :             .get_offloaded_timeline(child_timeline_id)
   11510            4 :             .unwrap()
   11511            4 :             .defuse_for_tenant_drop();
   11512            4 : 
   11513            4 :         Ok(())
   11514            4 :     }
   11515              : 
   11516              :     #[cfg(feature = "testing")]
   11517              :     #[tokio::test]
   11518            4 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11519            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11520            4 :         let (tenant, ctx) = harness.load().await;
   11521            4 : 
   11522          592 :         fn get_key(id: u32) -> Key {
   11523          592 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11524          592 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11525          592 :             key.field6 = id;
   11526          592 :             key
   11527          592 :         }
   11528            4 : 
   11529            4 :         let img_layer = (0..10)
   11530           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11531            4 :             .collect_vec();
   11532            4 : 
   11533            4 :         let delta1 = vec![(
   11534            4 :             get_key(1),
   11535            4 :             Lsn(0x20),
   11536            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11537            4 :         )];
   11538            4 :         let delta4 = vec![(
   11539            4 :             get_key(1),
   11540            4 :             Lsn(0x28),
   11541            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11542            4 :         )];
   11543            4 :         let delta2 = vec![
   11544            4 :             (
   11545            4 :                 get_key(1),
   11546            4 :                 Lsn(0x30),
   11547            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11548            4 :             ),
   11549            4 :             (
   11550            4 :                 get_key(1),
   11551            4 :                 Lsn(0x38),
   11552            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11553            4 :             ),
   11554            4 :         ];
   11555            4 :         let delta3 = vec![
   11556            4 :             (
   11557            4 :                 get_key(8),
   11558            4 :                 Lsn(0x48),
   11559            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11560            4 :             ),
   11561            4 :             (
   11562            4 :                 get_key(9),
   11563            4 :                 Lsn(0x48),
   11564            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11565            4 :             ),
   11566            4 :         ];
   11567            4 : 
   11568            4 :         let tline = tenant
   11569            4 :             .create_test_timeline_with_layers(
   11570            4 :                 TIMELINE_ID,
   11571            4 :                 Lsn(0x10),
   11572            4 :                 DEFAULT_PG_VERSION,
   11573            4 :                 &ctx,
   11574            4 :                 vec![], // in-memory layers
   11575            4 :                 vec![
   11576            4 :                     // delta1/2/4 only contain a single key but multiple updates
   11577            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11578            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11579            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11580            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11581            4 :                 ], // delta layers
   11582            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11583            4 :                 Lsn(0x50),
   11584            4 :             )
   11585            4 :             .await?;
   11586            4 :         {
   11587            4 :             tline
   11588            4 :                 .applied_gc_cutoff_lsn
   11589            4 :                 .lock_for_write()
   11590            4 :                 .store_and_unlock(Lsn(0x30))
   11591            4 :                 .wait()
   11592            4 :                 .await;
   11593            4 :             // Update GC info
   11594            4 :             let mut guard = tline.gc_info.write().unwrap();
   11595            4 :             *guard = GcInfo {
   11596            4 :                 retain_lsns: vec![
   11597            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11598            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11599            4 :                 ],
   11600            4 :                 cutoffs: GcCutoffs {
   11601            4 :                     time: Lsn(0x30),
   11602            4 :                     space: Lsn(0x30),
   11603            4 :                 },
   11604            4 :                 leases: Default::default(),
   11605            4 :                 within_ancestor_pitr: false,
   11606            4 :             };
   11607            4 :         }
   11608            4 : 
   11609            4 :         let expected_result = [
   11610            4 :             Bytes::from_static(b"value 0@0x10"),
   11611            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11612            4 :             Bytes::from_static(b"value 2@0x10"),
   11613            4 :             Bytes::from_static(b"value 3@0x10"),
   11614            4 :             Bytes::from_static(b"value 4@0x10"),
   11615            4 :             Bytes::from_static(b"value 5@0x10"),
   11616            4 :             Bytes::from_static(b"value 6@0x10"),
   11617            4 :             Bytes::from_static(b"value 7@0x10"),
   11618            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11619            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11620            4 :         ];
   11621            4 : 
   11622            4 :         let expected_result_at_gc_horizon = [
   11623            4 :             Bytes::from_static(b"value 0@0x10"),
   11624            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11625            4 :             Bytes::from_static(b"value 2@0x10"),
   11626            4 :             Bytes::from_static(b"value 3@0x10"),
   11627            4 :             Bytes::from_static(b"value 4@0x10"),
   11628            4 :             Bytes::from_static(b"value 5@0x10"),
   11629            4 :             Bytes::from_static(b"value 6@0x10"),
   11630            4 :             Bytes::from_static(b"value 7@0x10"),
   11631            4 :             Bytes::from_static(b"value 8@0x10"),
   11632            4 :             Bytes::from_static(b"value 9@0x10"),
   11633            4 :         ];
   11634            4 : 
   11635            4 :         let expected_result_at_lsn_20 = [
   11636            4 :             Bytes::from_static(b"value 0@0x10"),
   11637            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11638            4 :             Bytes::from_static(b"value 2@0x10"),
   11639            4 :             Bytes::from_static(b"value 3@0x10"),
   11640            4 :             Bytes::from_static(b"value 4@0x10"),
   11641            4 :             Bytes::from_static(b"value 5@0x10"),
   11642            4 :             Bytes::from_static(b"value 6@0x10"),
   11643            4 :             Bytes::from_static(b"value 7@0x10"),
   11644            4 :             Bytes::from_static(b"value 8@0x10"),
   11645            4 :             Bytes::from_static(b"value 9@0x10"),
   11646            4 :         ];
   11647            4 : 
   11648            4 :         let expected_result_at_lsn_10 = [
   11649            4 :             Bytes::from_static(b"value 0@0x10"),
   11650            4 :             Bytes::from_static(b"value 1@0x10"),
   11651            4 :             Bytes::from_static(b"value 2@0x10"),
   11652            4 :             Bytes::from_static(b"value 3@0x10"),
   11653            4 :             Bytes::from_static(b"value 4@0x10"),
   11654            4 :             Bytes::from_static(b"value 5@0x10"),
   11655            4 :             Bytes::from_static(b"value 6@0x10"),
   11656            4 :             Bytes::from_static(b"value 7@0x10"),
   11657            4 :             Bytes::from_static(b"value 8@0x10"),
   11658            4 :             Bytes::from_static(b"value 9@0x10"),
   11659            4 :         ];
   11660            4 : 
   11661           12 :         let verify_result = || async {
   11662           12 :             let gc_horizon = {
   11663           12 :                 let gc_info = tline.gc_info.read().unwrap();
   11664           12 :                 gc_info.cutoffs.time
   11665            4 :             };
   11666          132 :             for idx in 0..10 {
   11667          120 :                 assert_eq!(
   11668          120 :                     tline
   11669          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11670          120 :                         .await
   11671          120 :                         .unwrap(),
   11672          120 :                     &expected_result[idx]
   11673            4 :                 );
   11674          120 :                 assert_eq!(
   11675          120 :                     tline
   11676          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11677          120 :                         .await
   11678          120 :                         .unwrap(),
   11679          120 :                     &expected_result_at_gc_horizon[idx]
   11680            4 :                 );
   11681          120 :                 assert_eq!(
   11682          120 :                     tline
   11683          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11684          120 :                         .await
   11685          120 :                         .unwrap(),
   11686          120 :                     &expected_result_at_lsn_20[idx]
   11687            4 :                 );
   11688          120 :                 assert_eq!(
   11689          120 :                     tline
   11690          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11691          120 :                         .await
   11692          120 :                         .unwrap(),
   11693          120 :                     &expected_result_at_lsn_10[idx]
   11694            4 :                 );
   11695            4 :             }
   11696           24 :         };
   11697            4 : 
   11698            4 :         verify_result().await;
   11699            4 : 
   11700            4 :         let cancel = CancellationToken::new();
   11701            4 :         tline
   11702            4 :             .compact_with_gc(
   11703            4 :                 &cancel,
   11704            4 :                 CompactOptions {
   11705            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   11706            4 :                     ..Default::default()
   11707            4 :                 },
   11708            4 :                 &ctx,
   11709            4 :             )
   11710            4 :             .await
   11711            4 :             .unwrap();
   11712            4 :         verify_result().await;
   11713            4 : 
   11714            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11715            4 :         check_layer_map_key_eq(
   11716            4 :             all_layers,
   11717            4 :             vec![
   11718            4 :                 // The original image layer, not compacted
   11719            4 :                 PersistentLayerKey {
   11720            4 :                     key_range: get_key(0)..get_key(10),
   11721            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11722            4 :                     is_delta: false,
   11723            4 :                 },
   11724            4 :                 // Delta layer below the specified above_lsn not compacted
   11725            4 :                 PersistentLayerKey {
   11726            4 :                     key_range: get_key(1)..get_key(2),
   11727            4 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   11728            4 :                     is_delta: true,
   11729            4 :                 },
   11730            4 :                 // Delta layer compacted above the LSN
   11731            4 :                 PersistentLayerKey {
   11732            4 :                     key_range: get_key(1)..get_key(10),
   11733            4 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   11734            4 :                     is_delta: true,
   11735            4 :                 },
   11736            4 :             ],
   11737            4 :         );
   11738            4 : 
   11739            4 :         // compact again
   11740            4 :         tline
   11741            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11742            4 :             .await
   11743            4 :             .unwrap();
   11744            4 :         verify_result().await;
   11745            4 : 
   11746            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11747            4 :         check_layer_map_key_eq(
   11748            4 :             all_layers,
   11749            4 :             vec![
   11750            4 :                 // The compacted image layer (full key range)
   11751            4 :                 PersistentLayerKey {
   11752            4 :                     key_range: Key::MIN..Key::MAX,
   11753            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11754            4 :                     is_delta: false,
   11755            4 :                 },
   11756            4 :                 // All other data in the delta layer
   11757            4 :                 PersistentLayerKey {
   11758            4 :                     key_range: get_key(1)..get_key(10),
   11759            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11760            4 :                     is_delta: true,
   11761            4 :                 },
   11762            4 :             ],
   11763            4 :         );
   11764            4 : 
   11765            4 :         Ok(())
   11766            4 :     }
   11767              : 
   11768              :     #[cfg(feature = "testing")]
   11769              :     #[tokio::test]
   11770            4 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   11771            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   11772            4 :         let (tenant, ctx) = harness.load().await;
   11773            4 : 
   11774         1016 :         fn get_key(id: u32) -> Key {
   11775         1016 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11776         1016 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11777         1016 :             key.field6 = id;
   11778         1016 :             key
   11779         1016 :         }
   11780            4 : 
   11781            4 :         let img_layer = (0..10)
   11782           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11783            4 :             .collect_vec();
   11784            4 : 
   11785            4 :         let delta1 = vec![(
   11786            4 :             get_key(1),
   11787            4 :             Lsn(0x20),
   11788            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11789            4 :         )];
   11790            4 :         let delta4 = vec![(
   11791            4 :             get_key(1),
   11792            4 :             Lsn(0x28),
   11793            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11794            4 :         )];
   11795            4 :         let delta2 = vec![
   11796            4 :             (
   11797            4 :                 get_key(1),
   11798            4 :                 Lsn(0x30),
   11799            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11800            4 :             ),
   11801            4 :             (
   11802            4 :                 get_key(1),
   11803            4 :                 Lsn(0x38),
   11804            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11805            4 :             ),
   11806            4 :         ];
   11807            4 :         let delta3 = vec![
   11808            4 :             (
   11809            4 :                 get_key(8),
   11810            4 :                 Lsn(0x48),
   11811            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11812            4 :             ),
   11813            4 :             (
   11814            4 :                 get_key(9),
   11815            4 :                 Lsn(0x48),
   11816            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11817            4 :             ),
   11818            4 :         ];
   11819            4 : 
   11820            4 :         let tline = tenant
   11821            4 :             .create_test_timeline_with_layers(
   11822            4 :                 TIMELINE_ID,
   11823            4 :                 Lsn(0x10),
   11824            4 :                 DEFAULT_PG_VERSION,
   11825            4 :                 &ctx,
   11826            4 :                 vec![], // in-memory layers
   11827            4 :                 vec![
   11828            4 :                     // delta1/2/4 only contain a single key but multiple updates
   11829            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11830            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11831            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11832            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11833            4 :                 ], // delta layers
   11834            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11835            4 :                 Lsn(0x50),
   11836            4 :             )
   11837            4 :             .await?;
   11838            4 :         {
   11839            4 :             tline
   11840            4 :                 .applied_gc_cutoff_lsn
   11841            4 :                 .lock_for_write()
   11842            4 :                 .store_and_unlock(Lsn(0x30))
   11843            4 :                 .wait()
   11844            4 :                 .await;
   11845            4 :             // Update GC info
   11846            4 :             let mut guard = tline.gc_info.write().unwrap();
   11847            4 :             *guard = GcInfo {
   11848            4 :                 retain_lsns: vec![
   11849            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11850            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11851            4 :                 ],
   11852            4 :                 cutoffs: GcCutoffs {
   11853            4 :                     time: Lsn(0x30),
   11854            4 :                     space: Lsn(0x30),
   11855            4 :                 },
   11856            4 :                 leases: Default::default(),
   11857            4 :                 within_ancestor_pitr: false,
   11858            4 :             };
   11859            4 :         }
   11860            4 : 
   11861            4 :         let expected_result = [
   11862            4 :             Bytes::from_static(b"value 0@0x10"),
   11863            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11864            4 :             Bytes::from_static(b"value 2@0x10"),
   11865            4 :             Bytes::from_static(b"value 3@0x10"),
   11866            4 :             Bytes::from_static(b"value 4@0x10"),
   11867            4 :             Bytes::from_static(b"value 5@0x10"),
   11868            4 :             Bytes::from_static(b"value 6@0x10"),
   11869            4 :             Bytes::from_static(b"value 7@0x10"),
   11870            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11871            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11872            4 :         ];
   11873            4 : 
   11874            4 :         let expected_result_at_gc_horizon = [
   11875            4 :             Bytes::from_static(b"value 0@0x10"),
   11876            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11877            4 :             Bytes::from_static(b"value 2@0x10"),
   11878            4 :             Bytes::from_static(b"value 3@0x10"),
   11879            4 :             Bytes::from_static(b"value 4@0x10"),
   11880            4 :             Bytes::from_static(b"value 5@0x10"),
   11881            4 :             Bytes::from_static(b"value 6@0x10"),
   11882            4 :             Bytes::from_static(b"value 7@0x10"),
   11883            4 :             Bytes::from_static(b"value 8@0x10"),
   11884            4 :             Bytes::from_static(b"value 9@0x10"),
   11885            4 :         ];
   11886            4 : 
   11887            4 :         let expected_result_at_lsn_20 = [
   11888            4 :             Bytes::from_static(b"value 0@0x10"),
   11889            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11890            4 :             Bytes::from_static(b"value 2@0x10"),
   11891            4 :             Bytes::from_static(b"value 3@0x10"),
   11892            4 :             Bytes::from_static(b"value 4@0x10"),
   11893            4 :             Bytes::from_static(b"value 5@0x10"),
   11894            4 :             Bytes::from_static(b"value 6@0x10"),
   11895            4 :             Bytes::from_static(b"value 7@0x10"),
   11896            4 :             Bytes::from_static(b"value 8@0x10"),
   11897            4 :             Bytes::from_static(b"value 9@0x10"),
   11898            4 :         ];
   11899            4 : 
   11900            4 :         let expected_result_at_lsn_10 = [
   11901            4 :             Bytes::from_static(b"value 0@0x10"),
   11902            4 :             Bytes::from_static(b"value 1@0x10"),
   11903            4 :             Bytes::from_static(b"value 2@0x10"),
   11904            4 :             Bytes::from_static(b"value 3@0x10"),
   11905            4 :             Bytes::from_static(b"value 4@0x10"),
   11906            4 :             Bytes::from_static(b"value 5@0x10"),
   11907            4 :             Bytes::from_static(b"value 6@0x10"),
   11908            4 :             Bytes::from_static(b"value 7@0x10"),
   11909            4 :             Bytes::from_static(b"value 8@0x10"),
   11910            4 :             Bytes::from_static(b"value 9@0x10"),
   11911            4 :         ];
   11912            4 : 
   11913           20 :         let verify_result = || async {
   11914           20 :             let gc_horizon = {
   11915           20 :                 let gc_info = tline.gc_info.read().unwrap();
   11916           20 :                 gc_info.cutoffs.time
   11917            4 :             };
   11918          220 :             for idx in 0..10 {
   11919          200 :                 assert_eq!(
   11920          200 :                     tline
   11921          200 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11922          200 :                         .await
   11923          200 :                         .unwrap(),
   11924          200 :                     &expected_result[idx]
   11925            4 :                 );
   11926          200 :                 assert_eq!(
   11927          200 :                     tline
   11928          200 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11929          200 :                         .await
   11930          200 :                         .unwrap(),
   11931          200 :                     &expected_result_at_gc_horizon[idx]
   11932            4 :                 );
   11933          200 :                 assert_eq!(
   11934          200 :                     tline
   11935          200 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11936          200 :                         .await
   11937          200 :                         .unwrap(),
   11938          200 :                     &expected_result_at_lsn_20[idx]
   11939            4 :                 );
   11940          200 :                 assert_eq!(
   11941          200 :                     tline
   11942          200 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11943          200 :                         .await
   11944          200 :                         .unwrap(),
   11945          200 :                     &expected_result_at_lsn_10[idx]
   11946            4 :                 );
   11947            4 :             }
   11948           40 :         };
   11949            4 : 
   11950            4 :         verify_result().await;
   11951            4 : 
   11952            4 :         let cancel = CancellationToken::new();
   11953            4 : 
   11954            4 :         tline
   11955            4 :             .compact_with_gc(
   11956            4 :                 &cancel,
   11957            4 :                 CompactOptions {
   11958            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11959            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   11960            4 :                     ..Default::default()
   11961            4 :                 },
   11962            4 :                 &ctx,
   11963            4 :             )
   11964            4 :             .await
   11965            4 :             .unwrap();
   11966            4 :         verify_result().await;
   11967            4 : 
   11968            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11969            4 :         check_layer_map_key_eq(
   11970            4 :             all_layers,
   11971            4 :             vec![
   11972            4 :                 // The original image layer, not compacted
   11973            4 :                 PersistentLayerKey {
   11974            4 :                     key_range: get_key(0)..get_key(10),
   11975            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11976            4 :                     is_delta: false,
   11977            4 :                 },
   11978            4 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   11979            4 :                 // the layer 0x28-0x30 into one.
   11980            4 :                 PersistentLayerKey {
   11981            4 :                     key_range: get_key(1)..get_key(2),
   11982            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11983            4 :                     is_delta: true,
   11984            4 :                 },
   11985            4 :                 // Above the upper bound and untouched
   11986            4 :                 PersistentLayerKey {
   11987            4 :                     key_range: get_key(1)..get_key(2),
   11988            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11989            4 :                     is_delta: true,
   11990            4 :                 },
   11991            4 :                 // This layer is untouched
   11992            4 :                 PersistentLayerKey {
   11993            4 :                     key_range: get_key(8)..get_key(10),
   11994            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11995            4 :                     is_delta: true,
   11996            4 :                 },
   11997            4 :             ],
   11998            4 :         );
   11999            4 : 
   12000            4 :         tline
   12001            4 :             .compact_with_gc(
   12002            4 :                 &cancel,
   12003            4 :                 CompactOptions {
   12004            4 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12005            4 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12006            4 :                     ..Default::default()
   12007            4 :                 },
   12008            4 :                 &ctx,
   12009            4 :             )
   12010            4 :             .await
   12011            4 :             .unwrap();
   12012            4 :         verify_result().await;
   12013            4 : 
   12014            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12015            4 :         check_layer_map_key_eq(
   12016            4 :             all_layers,
   12017            4 :             vec![
   12018            4 :                 // The original image layer, not compacted
   12019            4 :                 PersistentLayerKey {
   12020            4 :                     key_range: get_key(0)..get_key(10),
   12021            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12022            4 :                     is_delta: false,
   12023            4 :                 },
   12024            4 :                 // Not in the compaction key range, uncompacted
   12025            4 :                 PersistentLayerKey {
   12026            4 :                     key_range: get_key(1)..get_key(2),
   12027            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12028            4 :                     is_delta: true,
   12029            4 :                 },
   12030            4 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12031            4 :                 PersistentLayerKey {
   12032            4 :                     key_range: get_key(1)..get_key(2),
   12033            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12034            4 :                     is_delta: true,
   12035            4 :                 },
   12036            4 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12037            4 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12038            4 :                 // becomes 0x50.
   12039            4 :                 PersistentLayerKey {
   12040            4 :                     key_range: get_key(8)..get_key(10),
   12041            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12042            4 :                     is_delta: true,
   12043            4 :                 },
   12044            4 :             ],
   12045            4 :         );
   12046            4 : 
   12047            4 :         // compact again
   12048            4 :         tline
   12049            4 :             .compact_with_gc(
   12050            4 :                 &cancel,
   12051            4 :                 CompactOptions {
   12052            4 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12053            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12054            4 :                     ..Default::default()
   12055            4 :                 },
   12056            4 :                 &ctx,
   12057            4 :             )
   12058            4 :             .await
   12059            4 :             .unwrap();
   12060            4 :         verify_result().await;
   12061            4 : 
   12062            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12063            4 :         check_layer_map_key_eq(
   12064            4 :             all_layers,
   12065            4 :             vec![
   12066            4 :                 // The original image layer, not compacted
   12067            4 :                 PersistentLayerKey {
   12068            4 :                     key_range: get_key(0)..get_key(10),
   12069            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12070            4 :                     is_delta: false,
   12071            4 :                 },
   12072            4 :                 // The range gets compacted
   12073            4 :                 PersistentLayerKey {
   12074            4 :                     key_range: get_key(1)..get_key(2),
   12075            4 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12076            4 :                     is_delta: true,
   12077            4 :                 },
   12078            4 :                 // Not touched during this iteration of compaction
   12079            4 :                 PersistentLayerKey {
   12080            4 :                     key_range: get_key(8)..get_key(10),
   12081            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12082            4 :                     is_delta: true,
   12083            4 :                 },
   12084            4 :             ],
   12085            4 :         );
   12086            4 : 
   12087            4 :         // final full compaction
   12088            4 :         tline
   12089            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12090            4 :             .await
   12091            4 :             .unwrap();
   12092            4 :         verify_result().await;
   12093            4 : 
   12094            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12095            4 :         check_layer_map_key_eq(
   12096            4 :             all_layers,
   12097            4 :             vec![
   12098            4 :                 // The compacted image layer (full key range)
   12099            4 :                 PersistentLayerKey {
   12100            4 :                     key_range: Key::MIN..Key::MAX,
   12101            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12102            4 :                     is_delta: false,
   12103            4 :                 },
   12104            4 :                 // All other data in the delta layer
   12105            4 :                 PersistentLayerKey {
   12106            4 :                     key_range: get_key(1)..get_key(10),
   12107            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12108            4 :                     is_delta: true,
   12109            4 :                 },
   12110            4 :             ],
   12111            4 :         );
   12112            4 : 
   12113            4 :         Ok(())
   12114            4 :     }
   12115              : 
   12116              :     #[cfg(feature = "testing")]
   12117              :     #[tokio::test]
   12118            4 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12119            4 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12120            4 :         let (tenant, ctx) = harness.load().await;
   12121            4 : 
   12122           52 :         fn get_key(id: u32) -> Key {
   12123           52 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12124           52 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12125           52 :             key.field6 = id;
   12126           52 :             key
   12127           52 :         }
   12128            4 : 
   12129            4 :         let img_layer = (0..10)
   12130           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12131            4 :             .collect_vec();
   12132            4 : 
   12133            4 :         let delta1 = vec![
   12134            4 :             (
   12135            4 :                 get_key(1),
   12136            4 :                 Lsn(0x20),
   12137            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12138            4 :             ),
   12139            4 :             (
   12140            4 :                 get_key(1),
   12141            4 :                 Lsn(0x24),
   12142            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12143            4 :             ),
   12144            4 :             (
   12145            4 :                 get_key(1),
   12146            4 :                 Lsn(0x28),
   12147            4 :                 // This record will fail to redo
   12148            4 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12149            4 :             ),
   12150            4 :         ];
   12151            4 : 
   12152            4 :         let tline = tenant
   12153            4 :             .create_test_timeline_with_layers(
   12154            4 :                 TIMELINE_ID,
   12155            4 :                 Lsn(0x10),
   12156            4 :                 DEFAULT_PG_VERSION,
   12157            4 :                 &ctx,
   12158            4 :                 vec![], // in-memory layers
   12159            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12160            4 :                     Lsn(0x20)..Lsn(0x30),
   12161            4 :                     delta1,
   12162            4 :                 )], // delta layers
   12163            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12164            4 :                 Lsn(0x50),
   12165            4 :             )
   12166            4 :             .await?;
   12167            4 :         {
   12168            4 :             tline
   12169            4 :                 .applied_gc_cutoff_lsn
   12170            4 :                 .lock_for_write()
   12171            4 :                 .store_and_unlock(Lsn(0x30))
   12172            4 :                 .wait()
   12173            4 :                 .await;
   12174            4 :             // Update GC info
   12175            4 :             let mut guard = tline.gc_info.write().unwrap();
   12176            4 :             *guard = GcInfo {
   12177            4 :                 retain_lsns: vec![],
   12178            4 :                 cutoffs: GcCutoffs {
   12179            4 :                     time: Lsn(0x30),
   12180            4 :                     space: Lsn(0x30),
   12181            4 :                 },
   12182            4 :                 leases: Default::default(),
   12183            4 :                 within_ancestor_pitr: false,
   12184            4 :             };
   12185            4 :         }
   12186            4 : 
   12187            4 :         let cancel = CancellationToken::new();
   12188            4 : 
   12189            4 :         // Compaction will fail, but should not fire any critical error.
   12190            4 :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12191            4 :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12192            4 :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12193            4 :         let res = tline
   12194            4 :             .compact_with_gc(
   12195            4 :                 &cancel,
   12196            4 :                 CompactOptions {
   12197            4 :                     compact_key_range: None,
   12198            4 :                     compact_lsn_range: None,
   12199            4 :                     ..Default::default()
   12200            4 :                 },
   12201            4 :                 &ctx,
   12202            4 :             )
   12203            4 :             .await;
   12204            4 :         assert!(res.is_err());
   12205            4 : 
   12206            4 :         Ok(())
   12207            4 :     }
   12208              : 
   12209              :     #[cfg(feature = "testing")]
   12210              :     #[tokio::test]
   12211            4 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12212            4 :         use pageserver_api::models::TimelineVisibilityState;
   12213            4 : 
   12214            4 :         use crate::tenant::size::gather_inputs;
   12215            4 : 
   12216            4 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12217            4 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12218            4 :             pitr_interval: Some(Duration::ZERO),
   12219            4 :             ..Default::default()
   12220            4 :         };
   12221            4 :         let harness = TenantHarness::create_custom(
   12222            4 :             "test_synthetic_size_calculation_with_invisible_branches",
   12223            4 :             tenant_conf,
   12224            4 :             TenantId::generate(),
   12225            4 :             ShardIdentity::unsharded(),
   12226            4 :             Generation::new(0xdeadbeef),
   12227            4 :         )
   12228            4 :         .await?;
   12229            4 :         let (tenant, ctx) = harness.load().await;
   12230            4 :         let main_tline = tenant
   12231            4 :             .create_test_timeline_with_layers(
   12232            4 :                 TIMELINE_ID,
   12233            4 :                 Lsn(0x10),
   12234            4 :                 DEFAULT_PG_VERSION,
   12235            4 :                 &ctx,
   12236            4 :                 vec![],
   12237            4 :                 vec![],
   12238            4 :                 vec![],
   12239            4 :                 Lsn(0x100),
   12240            4 :             )
   12241            4 :             .await?;
   12242            4 : 
   12243            4 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12244            4 :         tenant
   12245            4 :             .branch_timeline_test_with_layers(
   12246            4 :                 &main_tline,
   12247            4 :                 snapshot1,
   12248            4 :                 Some(Lsn(0x20)),
   12249            4 :                 &ctx,
   12250            4 :                 vec![],
   12251            4 :                 vec![],
   12252            4 :                 Lsn(0x50),
   12253            4 :             )
   12254            4 :             .await?;
   12255            4 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12256            4 :         tenant
   12257            4 :             .branch_timeline_test_with_layers(
   12258            4 :                 &main_tline,
   12259            4 :                 snapshot2,
   12260            4 :                 Some(Lsn(0x30)),
   12261            4 :                 &ctx,
   12262            4 :                 vec![],
   12263            4 :                 vec![],
   12264            4 :                 Lsn(0x50),
   12265            4 :             )
   12266            4 :             .await?;
   12267            4 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12268            4 :         tenant
   12269            4 :             .branch_timeline_test_with_layers(
   12270            4 :                 &main_tline,
   12271            4 :                 snapshot3,
   12272            4 :                 Some(Lsn(0x40)),
   12273            4 :                 &ctx,
   12274            4 :                 vec![],
   12275            4 :                 vec![],
   12276            4 :                 Lsn(0x50),
   12277            4 :             )
   12278            4 :             .await?;
   12279            4 :         let limit = Arc::new(Semaphore::new(1));
   12280            4 :         let max_retention_period = None;
   12281            4 :         let mut logical_size_cache = HashMap::new();
   12282            4 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12283            4 :         let cancel = CancellationToken::new();
   12284            4 : 
   12285            4 :         let inputs = gather_inputs(
   12286            4 :             &tenant,
   12287            4 :             &limit,
   12288            4 :             max_retention_period,
   12289            4 :             &mut logical_size_cache,
   12290            4 :             cause,
   12291            4 :             &cancel,
   12292            4 :             &ctx,
   12293            4 :         )
   12294            4 :         .instrument(info_span!(
   12295            4 :             "gather_inputs",
   12296            4 :             tenant_id = "unknown",
   12297            4 :             shard_id = "unknown",
   12298            4 :         ))
   12299            4 :         .await?;
   12300            4 :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12301            4 :         use LsnKind::*;
   12302            4 :         use tenant_size_model::Segment;
   12303            4 :         let ModelInputs { mut segments, .. } = inputs;
   12304           60 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12305           24 :         for segment in segments.iter_mut() {
   12306           24 :             segment.segment.parent = None; // We don't care about the parent for the test
   12307           24 :             segment.segment.size = None; // We don't care about the size for the test
   12308           24 :         }
   12309            4 :         assert_eq!(
   12310            4 :             segments,
   12311            4 :             [
   12312            4 :                 SegmentMeta {
   12313            4 :                     segment: Segment {
   12314            4 :                         parent: None,
   12315            4 :                         lsn: 0x10,
   12316            4 :                         size: None,
   12317            4 :                         needed: false,
   12318            4 :                     },
   12319            4 :                     timeline_id: TIMELINE_ID,
   12320            4 :                     kind: BranchStart,
   12321            4 :                 },
   12322            4 :                 SegmentMeta {
   12323            4 :                     segment: Segment {
   12324            4 :                         parent: None,
   12325            4 :                         lsn: 0x20,
   12326            4 :                         size: None,
   12327            4 :                         needed: false,
   12328            4 :                     },
   12329            4 :                     timeline_id: TIMELINE_ID,
   12330            4 :                     kind: BranchPoint,
   12331            4 :                 },
   12332            4 :                 SegmentMeta {
   12333            4 :                     segment: Segment {
   12334            4 :                         parent: None,
   12335            4 :                         lsn: 0x30,
   12336            4 :                         size: None,
   12337            4 :                         needed: false,
   12338            4 :                     },
   12339            4 :                     timeline_id: TIMELINE_ID,
   12340            4 :                     kind: BranchPoint,
   12341            4 :                 },
   12342            4 :                 SegmentMeta {
   12343            4 :                     segment: Segment {
   12344            4 :                         parent: None,
   12345            4 :                         lsn: 0x40,
   12346            4 :                         size: None,
   12347            4 :                         needed: false,
   12348            4 :                     },
   12349            4 :                     timeline_id: TIMELINE_ID,
   12350            4 :                     kind: BranchPoint,
   12351            4 :                 },
   12352            4 :                 SegmentMeta {
   12353            4 :                     segment: Segment {
   12354            4 :                         parent: None,
   12355            4 :                         lsn: 0x100,
   12356            4 :                         size: None,
   12357            4 :                         needed: false,
   12358            4 :                     },
   12359            4 :                     timeline_id: TIMELINE_ID,
   12360            4 :                     kind: GcCutOff,
   12361            4 :                 }, // we need to retain everything above the last branch point
   12362            4 :                 SegmentMeta {
   12363            4 :                     segment: Segment {
   12364            4 :                         parent: None,
   12365            4 :                         lsn: 0x100,
   12366            4 :                         size: None,
   12367            4 :                         needed: true,
   12368            4 :                     },
   12369            4 :                     timeline_id: TIMELINE_ID,
   12370            4 :                     kind: BranchEnd,
   12371            4 :                 },
   12372            4 :             ]
   12373            4 :         );
   12374            4 : 
   12375            4 :         main_tline
   12376            4 :             .remote_client
   12377            4 :             .schedule_index_upload_for_timeline_invisible_state(
   12378            4 :                 TimelineVisibilityState::Invisible,
   12379            4 :             )?;
   12380            4 :         main_tline.remote_client.wait_completion().await?;
   12381            4 :         let inputs = gather_inputs(
   12382            4 :             &tenant,
   12383            4 :             &limit,
   12384            4 :             max_retention_period,
   12385            4 :             &mut logical_size_cache,
   12386            4 :             cause,
   12387            4 :             &cancel,
   12388            4 :             &ctx,
   12389            4 :         )
   12390            4 :         .instrument(info_span!(
   12391            4 :             "gather_inputs",
   12392            4 :             tenant_id = "unknown",
   12393            4 :             shard_id = "unknown",
   12394            4 :         ))
   12395            4 :         .await?;
   12396            4 :         let ModelInputs { mut segments, .. } = inputs;
   12397           56 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12398           20 :         for segment in segments.iter_mut() {
   12399           20 :             segment.segment.parent = None; // We don't care about the parent for the test
   12400           20 :             segment.segment.size = None; // We don't care about the size for the test
   12401           20 :         }
   12402            4 :         assert_eq!(
   12403            4 :             segments,
   12404            4 :             [
   12405            4 :                 SegmentMeta {
   12406            4 :                     segment: Segment {
   12407            4 :                         parent: None,
   12408            4 :                         lsn: 0x10,
   12409            4 :                         size: None,
   12410            4 :                         needed: false,
   12411            4 :                     },
   12412            4 :                     timeline_id: TIMELINE_ID,
   12413            4 :                     kind: BranchStart,
   12414            4 :                 },
   12415            4 :                 SegmentMeta {
   12416            4 :                     segment: Segment {
   12417            4 :                         parent: None,
   12418            4 :                         lsn: 0x20,
   12419            4 :                         size: None,
   12420            4 :                         needed: false,
   12421            4 :                     },
   12422            4 :                     timeline_id: TIMELINE_ID,
   12423            4 :                     kind: BranchPoint,
   12424            4 :                 },
   12425            4 :                 SegmentMeta {
   12426            4 :                     segment: Segment {
   12427            4 :                         parent: None,
   12428            4 :                         lsn: 0x30,
   12429            4 :                         size: None,
   12430            4 :                         needed: false,
   12431            4 :                     },
   12432            4 :                     timeline_id: TIMELINE_ID,
   12433            4 :                     kind: BranchPoint,
   12434            4 :                 },
   12435            4 :                 SegmentMeta {
   12436            4 :                     segment: Segment {
   12437            4 :                         parent: None,
   12438            4 :                         lsn: 0x40,
   12439            4 :                         size: None,
   12440            4 :                         needed: false,
   12441            4 :                     },
   12442            4 :                     timeline_id: TIMELINE_ID,
   12443            4 :                     kind: BranchPoint,
   12444            4 :                 },
   12445            4 :                 SegmentMeta {
   12446            4 :                     segment: Segment {
   12447            4 :                         parent: None,
   12448            4 :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12449            4 :                         size: None,
   12450            4 :                         needed: true,
   12451            4 :                     },
   12452            4 :                     timeline_id: TIMELINE_ID,
   12453            4 :                     kind: BranchEnd,
   12454            4 :                 },
   12455            4 :             ]
   12456            4 :         );
   12457            4 :         Ok(())
   12458            4 :     }
   12459              : }
        

Generated by: LCOV version 2.1-beta