LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: aca806cab4756d7eb6a304846130f4a73a5d5393.info Lines: 78.4 % 9556 7496
Test Date: 2025-04-24 20:31:15 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 [`TenantShard`] 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         1392 :     fn new(
     175         1392 :         tenant_conf: pageserver_api::models::TenantConfig,
     176         1392 :         location: AttachedLocationConfig,
     177         1392 :     ) -> 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         1392 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     184         1392 :             Some(
     185         1392 :                 tokio::time::Instant::now()
     186         1392 :                     + tenant_conf
     187         1392 :                         .lsn_lease_length
     188         1392 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     189         1392 :             )
     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         1392 :         Self {
     197         1392 :             tenant_conf,
     198         1392 :             location,
     199         1392 :             lsn_lease_deadline,
     200         1392 :         }
     201         1392 :     }
     202              : 
     203         1392 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     204         1392 :         match &location_conf.mode {
     205         1392 :             LocationMode::Attached(attach_conf) => {
     206         1392 :                 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         1392 :     }
     215              : 
     216         4572 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     217         4572 :         self.lsn_lease_deadline
     218         4572 :             .map(|d| tokio::time::Instant::now() < d)
     219         4572 :             .unwrap_or(false)
     220         4572 :     }
     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 TenantShard {
     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 [`TenantShard`] 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 [`TenantShard::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 TenantShard such as the page service must take this Gate to avoid
     341              :     // trying to use a TenantShard which is shutting down.
     342              :     pub(crate) gate: Gate,
     343              : 
     344              :     /// Throttle applied at the top of [`Timeline::get`].
     345              :     /// All [`TenantShard::timelines`] of a given [`TenantShard`] 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 TenantShard {
     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           60 :     fn drop(&mut self) {
     398           60 :         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           60 :             Self::Test(_) => {
     407           60 :                 // Not applicable to test redo manager
     408           60 :             }
     409              :         }
     410           60 :     }
     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         1392 :     fn from(mgr: harness::TestRedoManager) -> Self {
     440         1392 :         Self::Test(mgr)
     441         1392 :     }
     442              : }
     443              : 
     444              : impl WalRedoManager {
     445           36 :     pub(crate) async fn shutdown(&self) -> bool {
     446           36 :         match self {
     447            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     448              :             #[cfg(test)]
     449              :             Self::Test(_) => {
     450              :                 // Not applicable to test redo manager
     451           36 :                 true
     452              :             }
     453              :         }
     454           36 :     }
     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       321288 :     pub async fn request_redo(
     470       321288 :         &self,
     471       321288 :         key: pageserver_api::key::Key,
     472       321288 :         lsn: Lsn,
     473       321288 :         base_img: Option<(Lsn, bytes::Bytes)>,
     474       321288 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     475       321288 :         pg_version: u32,
     476       321288 :         redo_attempt_type: RedoAttemptType,
     477       321288 :     ) -> Result<bytes::Bytes, walredo::Error> {
     478       321288 :         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       321288 :             Self::Test(mgr) => {
     485       321288 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     486       321288 :                     .await
     487              :             }
     488              :         }
     489       321288 :     }
     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           12 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     533           12 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     534           12 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     535           12 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     536           12 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     537           12 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     538           12 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     539           12 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     540              :             } else {
     541            0 :                 (None, None)
     542              :             };
     543           12 :         let archived_at = timeline
     544           12 :             .remote_client
     545           12 :             .archived_at_stopped_queue()?
     546           12 :             .expect("must be called on an archived timeline");
     547           12 :         Ok(Self {
     548           12 :             tenant_shard_id: timeline.tenant_shard_id,
     549           12 :             timeline_id: timeline.timeline_id,
     550           12 :             ancestor_timeline_id,
     551           12 :             ancestor_retain_lsn,
     552           12 :             archived_at,
     553           12 : 
     554           12 :             delete_progress: timeline.delete_progress.clone(),
     555           12 :             deleted_from_ancestor: AtomicBool::new(false),
     556           12 :         })
     557           12 :     }
     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           12 :     fn manifest(&self) -> OffloadedTimelineManifest {
     578           12 :         let Self {
     579           12 :             timeline_id,
     580           12 :             ancestor_timeline_id,
     581           12 :             ancestor_retain_lsn,
     582           12 :             archived_at,
     583           12 :             ..
     584           12 :         } = self;
     585           12 :         OffloadedTimelineManifest {
     586           12 :             timeline_id: *timeline_id,
     587           12 :             ancestor_timeline_id: *ancestor_timeline_id,
     588           12 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     589           12 :             archived_at: *archived_at,
     590           12 :         }
     591           12 :     }
     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           12 :     fn defuse_for_tenant_drop(&self) {
     621           12 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     622           12 :     }
     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           12 :     fn drop(&mut self) {
     633           12 :         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           12 :         }
     639           12 :     }
     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           12 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     672           12 :         match self {
     673           12 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     674            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     675              :         }
     676           12 :     }
     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 [`TenantShard::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 [`TenantShard::create_timeline`] call in  [`TenantShard::start_creating_timeline`] in  [`TenantShard::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 [`TenantShard::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 [`TenantShard::create_timeline`].
     947              : enum CreateTimelineResult {
     948              :     Created(Arc<Timeline>),
     949              :     Idempotent(Arc<Timeline>),
     950              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`TenantShard::timelines`] when
     951              :     /// we return this result, nor will this concrete object ever be added there.
     952              :     /// Cf method comment on [`TenantShard::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         1416 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     972         1416 :         match self {
     973         1416 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     974         1416 :         }
     975         1416 :     }
     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 TenantShard {
    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           36 :     async fn timeline_init_and_sync(
    1097           36 :         self: &Arc<Self>,
    1098           36 :         timeline_id: TimelineId,
    1099           36 :         resources: TimelineResources,
    1100           36 :         mut index_part: IndexPart,
    1101           36 :         metadata: TimelineMetadata,
    1102           36 :         previous_heatmap: Option<PreviousHeatmap>,
    1103           36 :         ancestor: Option<Arc<Timeline>>,
    1104           36 :         cause: LoadTimelineCause,
    1105           36 :         ctx: &RequestContext,
    1106           36 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1107           36 :         let tenant_id = self.tenant_shard_id;
    1108           36 : 
    1109           36 :         let import_pgdata = index_part.import_pgdata.take();
    1110           36 :         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           36 :                 if metadata.ancestor_timeline().is_none() {
    1118           24 :                     CreateTimelineIdempotency::Bootstrap {
    1119           24 :                         pg_version: metadata.pg_version(),
    1120           24 :                     }
    1121              :                 } else {
    1122           12 :                     CreateTimelineIdempotency::Branch {
    1123           12 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1124           12 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1125           12 :                     }
    1126              :                 }
    1127              :             }
    1128              :         };
    1129              : 
    1130           36 :         let (timeline, timeline_ctx) = self.create_timeline_struct(
    1131           36 :             timeline_id,
    1132           36 :             &metadata,
    1133           36 :             previous_heatmap,
    1134           36 :             ancestor.clone(),
    1135           36 :             resources,
    1136           36 :             CreateTimelineCause::Load,
    1137           36 :             idempotency.clone(),
    1138           36 :             index_part.gc_compaction.clone(),
    1139           36 :             index_part.rel_size_migration.clone(),
    1140           36 :             ctx,
    1141           36 :         )?;
    1142           36 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1143           36 :         anyhow::ensure!(
    1144           36 :             disk_consistent_lsn.is_valid(),
    1145            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1146              :         );
    1147           36 :         assert_eq!(
    1148           36 :             disk_consistent_lsn,
    1149           36 :             metadata.disk_consistent_lsn(),
    1150            0 :             "these are used interchangeably"
    1151              :         );
    1152              : 
    1153           36 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1154              : 
    1155           36 :         timeline
    1156           36 :             .load_layer_map(disk_consistent_lsn, index_part)
    1157           36 :             .await
    1158           36 :             .with_context(|| {
    1159            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1160           36 :             })?;
    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           36 :         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           36 :         }
    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           36 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1234           36 :                     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           36 :                         Entry::Vacant(v) => {
    1242           36 :                             v.insert(Arc::clone(&timeline));
    1243           36 :                             timeline.maybe_spawn_flush_loop();
    1244           36 :                         }
    1245              :                     }
    1246              :                 }
    1247              : 
    1248              :                 // Sanity check: a timeline should have some content.
    1249           36 :                 anyhow::ensure!(
    1250           36 :                     ancestor.is_some()
    1251           24 :                         || timeline
    1252           24 :                             .layers
    1253           24 :                             .read()
    1254           24 :                             .await
    1255           24 :                             .layer_map()
    1256           24 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1257           24 :                             .iter_historic_layers()
    1258           24 :                             .next()
    1259           24 :                             .is_some(),
    1260            0 :                     "Timeline has no ancestor and no layer files"
    1261              :                 );
    1262              : 
    1263           36 :                 match cause {
    1264           36 :                     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           36 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1283              :             }
    1284              :         }
    1285           36 :     }
    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<TenantShard>, 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(TenantShard::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 TenantShard: 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: &TenantShard, 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           36 :                 .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           36 :                 .map(|(id, tl)| (id, Some(tl)))
    1595            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1596              :                 .collect(),
    1597              :         })
    1598              :     }
    1599              : 
    1600         1392 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1601         1392 :         if !self.conf.load_previous_heatmap {
    1602            0 :             return None;
    1603         1392 :         }
    1604         1392 : 
    1605         1392 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1606         1392 :         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         1392 :             Err(err) => match err.kind() {
    1615         1392 :                 std::io::ErrorKind::NotFound => None,
    1616              :                 _ => {
    1617            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1618            0 :                     None
    1619              :                 }
    1620              :             },
    1621              :         }
    1622         1392 :     }
    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         1392 :     async fn attach(
    1630         1392 :         self: &Arc<TenantShard>,
    1631         1392 :         preload: Option<TenantPreload>,
    1632         1392 :         ctx: &RequestContext,
    1633         1392 :     ) -> anyhow::Result<()> {
    1634         1392 :         span::debug_assert_current_span_has_tenant_id();
    1635         1392 : 
    1636         1392 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1637              : 
    1638         1392 :         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         1392 :         let mut offloaded_timeline_ids = HashSet::new();
    1645         1392 :         let mut offloaded_timelines_list = Vec::new();
    1646         1392 :         if let Some(tenant_manifest) = &preload.tenant_manifest {
    1647           36 :             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         1356 :         }
    1655              :         // Complete deletions for offloaded timeline id's from manifest.
    1656              :         // The manifest will be uploaded later in this function.
    1657         1392 :         offloaded_timelines_list
    1658         1392 :             .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         1392 :         });
    1668         1392 : 
    1669         1392 :         let mut timelines_to_resume_deletions = vec![];
    1670         1392 : 
    1671         1392 :         let mut remote_index_and_client = HashMap::new();
    1672         1392 :         let mut timeline_ancestors = HashMap::new();
    1673         1392 :         let mut existent_timelines = HashSet::new();
    1674         1428 :         for (timeline_id, preload) in preload.timelines {
    1675           36 :             let Some(preload) = preload else { continue };
    1676              :             // This is an invariant of the `preload` function's API
    1677           36 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1678           36 :             let index_part = match preload.index_part {
    1679           36 :                 Ok(i) => {
    1680           36 :                     debug!("remote index part exists for timeline {timeline_id}");
    1681              :                     // We found index_part on the remote, this is the standard case.
    1682           36 :                     existent_timelines.insert(timeline_id);
    1683           36 :                     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           36 :             match index_part {
    1713           36 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1714           36 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1715           36 :                     remote_index_and_client.insert(
    1716           36 :                         timeline_id,
    1717           36 :                         (index_part, preload.client, preload.previous_heatmap),
    1718           36 :                     );
    1719           36 :                 }
    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         1392 :         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         1392 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1736         1428 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1737           36 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1738           36 :                 .remove(&timeline_id)
    1739           36 :                 .expect("just put it in above");
    1740              : 
    1741           36 :             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           36 :             }
    1750              : 
    1751              :             // TODO again handle early failure
    1752           36 :             let effect = self
    1753           36 :                 .load_remote_timeline(
    1754           36 :                     timeline_id,
    1755           36 :                     index_part,
    1756           36 :                     remote_metadata,
    1757           36 :                     previous_heatmap,
    1758           36 :                     self.get_timeline_resources_for(remote_client),
    1759           36 :                     LoadTimelineCause::Attach,
    1760           36 :                     ctx,
    1761           36 :                 )
    1762           36 :                 .await
    1763           36 :                 .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           36 :                 })?;
    1769              : 
    1770           36 :             match effect {
    1771           36 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1772           36 :                     // activation happens later, on Tenant::activate
    1773           36 :                 }
    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         1392 :         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         1392 :         {
    1812         1392 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1813         1392 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1814         1392 :         }
    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         1392 :             let mut guard = self.remote_tenant_manifest.lock().await;
    1822         1392 :             assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
    1823         1392 :             *guard = preload.tenant_manifest;
    1824         1392 :         }
    1825         1392 :         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         1392 :         self.clean_up_timelines(&existent_timelines)?;
    1830              : 
    1831         1392 :         self.gc_block.set_scanned(gc_blocks);
    1832         1392 : 
    1833         1392 :         fail::fail_point!("attach-before-activate", |_| {
    1834            0 :             anyhow::bail!("attach-before-activate");
    1835         1392 :         });
    1836         1392 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1837              : 
    1838         1392 :         info!("Done");
    1839              : 
    1840         1392 :         Ok(())
    1841         1392 :     }
    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         1392 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1847         1392 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1848              : 
    1849         1392 :         let entries = match timelines_dir.read_dir_utf8() {
    1850         1392 :             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         1440 :         for entry in entries {
    1861           48 :             let entry = entry.context("read timeline dir entry")?;
    1862           48 :             let entry_path = entry.path();
    1863              : 
    1864           48 :             let purge = if crate::is_temporary(entry_path) {
    1865            0 :                 true
    1866              :             } else {
    1867           48 :                 match TimelineId::try_from(entry_path.file_name()) {
    1868           48 :                     Ok(i) => {
    1869           48 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1870           48 :                         !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           48 :             if purge {
    1883           12 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1884           12 :                 if let Err(e) = match entry.file_type() {
    1885           12 :                     Ok(t) => if t.is_dir() {
    1886           12 :                         std::fs::remove_dir_all(entry_path)
    1887              :                     } else {
    1888            0 :                         std::fs::remove_file(entry_path)
    1889              :                     }
    1890           12 :                     .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           12 :                 }
    1895           36 :             }
    1896              :         }
    1897              : 
    1898         1392 :         Ok(())
    1899         1392 :     }
    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         1392 :     async fn load_timelines_metadata(
    1960         1392 :         self: &Arc<TenantShard>,
    1961         1392 :         timeline_ids: HashSet<TimelineId>,
    1962         1392 :         remote_storage: &GenericRemoteStorage,
    1963         1392 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    1964         1392 :         cancel: CancellationToken,
    1965         1392 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1966         1392 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    1967         1392 : 
    1968         1392 :         let mut part_downloads = JoinSet::new();
    1969         1428 :         for timeline_id in timeline_ids {
    1970           36 :             let cancel_clone = cancel.clone();
    1971           36 : 
    1972           36 :             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           36 :             });
    1979           36 :             part_downloads.spawn(
    1980           36 :                 self.load_timeline_metadata(
    1981           36 :                     timeline_id,
    1982           36 :                     remote_storage.clone(),
    1983           36 :                     previous_timeline_heatmap,
    1984           36 :                     cancel_clone,
    1985           36 :                 )
    1986           36 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    1987              :             );
    1988              :         }
    1989              : 
    1990         1392 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1991              : 
    1992              :         loop {
    1993         1428 :             tokio::select!(
    1994         1428 :                 next = part_downloads.join_next() => {
    1995         1428 :                     match next {
    1996           36 :                         Some(result) => {
    1997           36 :                             let preload = result.context("join preload task")?;
    1998           36 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1999              :                         },
    2000              :                         None => {
    2001         1392 :                             break;
    2002              :                         }
    2003              :                     }
    2004              :                 },
    2005         1428 :                 _ = cancel.cancelled() => {
    2006            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    2007              :                 }
    2008              :             )
    2009              :         }
    2010              : 
    2011         1392 :         Ok(timeline_preloads)
    2012         1392 :     }
    2013              : 
    2014           36 :     fn build_timeline_client(
    2015           36 :         &self,
    2016           36 :         timeline_id: TimelineId,
    2017           36 :         remote_storage: GenericRemoteStorage,
    2018           36 :     ) -> RemoteTimelineClient {
    2019           36 :         RemoteTimelineClient::new(
    2020           36 :             remote_storage.clone(),
    2021           36 :             self.deletion_queue_client.clone(),
    2022           36 :             self.conf,
    2023           36 :             self.tenant_shard_id,
    2024           36 :             timeline_id,
    2025           36 :             self.generation,
    2026           36 :             &self.tenant_conf.load().location,
    2027           36 :         )
    2028           36 :     }
    2029              : 
    2030           36 :     fn load_timeline_metadata(
    2031           36 :         self: &Arc<TenantShard>,
    2032           36 :         timeline_id: TimelineId,
    2033           36 :         remote_storage: GenericRemoteStorage,
    2034           36 :         previous_heatmap: Option<PreviousHeatmap>,
    2035           36 :         cancel: CancellationToken,
    2036           36 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2037           36 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2038           36 :         async move {
    2039           36 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2040           36 :             debug!("starting index part download");
    2041              : 
    2042           36 :             let index_part = client.download_index_file(&cancel).await;
    2043              : 
    2044           36 :             debug!("finished index part download");
    2045              : 
    2046           36 :             TimelinePreload {
    2047           36 :                 client,
    2048           36 :                 timeline_id,
    2049           36 :                 index_part,
    2050           36 :                 previous_heatmap,
    2051           36 :             }
    2052           36 :         }
    2053           36 :     }
    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           12 :     pub fn get_offloaded_timeline(
    2347           12 :         &self,
    2348           12 :         timeline_id: TimelineId,
    2349           12 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2350           12 :         self.timelines_offloaded
    2351           12 :             .lock()
    2352           12 :             .unwrap()
    2353           12 :             .get(&timeline_id)
    2354           12 :             .map(Arc::clone)
    2355           12 :             .ok_or(GetTimelineError::NotFound {
    2356           12 :                 tenant_id: self.tenant_shard_id,
    2357           12 :                 timeline_id,
    2358           12 :             })
    2359           12 :     }
    2360              : 
    2361           24 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2362           24 :         self.tenant_shard_id
    2363           24 :     }
    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         1332 :     pub fn get_timeline(
    2368         1332 :         &self,
    2369         1332 :         timeline_id: TimelineId,
    2370         1332 :         active_only: bool,
    2371         1332 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2372         1332 :         let timelines_accessor = self.timelines.lock().unwrap();
    2373         1332 :         let timeline = timelines_accessor
    2374         1332 :             .get(&timeline_id)
    2375         1332 :             .ok_or(GetTimelineError::NotFound {
    2376         1332 :                 tenant_id: self.tenant_shard_id,
    2377         1332 :                 timeline_id,
    2378         1332 :             })?;
    2379              : 
    2380         1320 :         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         1320 :             Ok(Arc::clone(timeline))
    2388              :         }
    2389         1332 :     }
    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           24 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2394           24 :         self.timelines
    2395           24 :             .lock()
    2396           24 :             .unwrap()
    2397           24 :             .values()
    2398           24 :             .map(Arc::clone)
    2399           24 :             .collect()
    2400           24 :     }
    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 [`TenantShard::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 [`TenantShard::load_remote_timeline`] / [`TenantShard::attach`].
    2436              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2437              :     /// to the [`TenantShard::timelines`].
    2438              :     ///
    2439              :     /// Tests should use `TenantShard::create_test_timeline` to set up the minimum required metadata keys.
    2440         1344 :     pub(crate) async fn create_empty_timeline(
    2441         1344 :         self: &Arc<Self>,
    2442         1344 :         new_timeline_id: TimelineId,
    2443         1344 :         initdb_lsn: Lsn,
    2444         1344 :         pg_version: u32,
    2445         1344 :         ctx: &RequestContext,
    2446         1344 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2447         1344 :         anyhow::ensure!(
    2448         1344 :             self.is_active(),
    2449            0 :             "Cannot create empty timelines on inactive tenant"
    2450              :         );
    2451              : 
    2452              :         // Protect against concurrent attempts to use this TimelineId
    2453         1344 :         let create_guard = match self
    2454         1344 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2455         1344 :             .await?
    2456              :         {
    2457         1332 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2458              :             StartCreatingTimelineResult::Idempotent(_) => {
    2459            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2460              :             }
    2461              :         };
    2462              : 
    2463         1332 :         let new_metadata = TimelineMetadata::new(
    2464         1332 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2465         1332 :             // make it valid, before calling finish_creation()
    2466         1332 :             Lsn(0),
    2467         1332 :             None,
    2468         1332 :             None,
    2469         1332 :             Lsn(0),
    2470         1332 :             initdb_lsn,
    2471         1332 :             initdb_lsn,
    2472         1332 :             pg_version,
    2473         1332 :         );
    2474         1332 :         self.prepare_new_timeline(
    2475         1332 :             new_timeline_id,
    2476         1332 :             &new_metadata,
    2477         1332 :             create_guard,
    2478         1332 :             initdb_lsn,
    2479         1332 :             None,
    2480         1332 :             None,
    2481         1332 :             ctx,
    2482         1332 :         )
    2483         1332 :         .await
    2484         1344 :     }
    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         1284 :     pub async fn create_test_timeline(
    2493         1284 :         self: &Arc<Self>,
    2494         1284 :         new_timeline_id: TimelineId,
    2495         1284 :         initdb_lsn: Lsn,
    2496         1284 :         pg_version: u32,
    2497         1284 :         ctx: &RequestContext,
    2498         1284 :     ) -> anyhow::Result<Arc<Timeline>> {
    2499         1284 :         let (uninit_tl, ctx) = self
    2500         1284 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2501         1284 :             .await?;
    2502         1284 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2503         1284 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2504              : 
    2505              :         // Setup minimum keys required for the timeline to be usable.
    2506         1284 :         let mut modification = tline.begin_modification(initdb_lsn);
    2507         1284 :         modification
    2508         1284 :             .init_empty_test_timeline()
    2509         1284 :             .context("init_empty_test_timeline")?;
    2510         1284 :         modification
    2511         1284 :             .commit(&ctx)
    2512         1284 :             .await
    2513         1284 :             .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         1284 :         tline.maybe_spawn_flush_loop();
    2517         1284 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2518              : 
    2519              :         // Make sure the freeze_and_flush reaches remote storage.
    2520         1284 :         tline.remote_client.wait_completion().await.unwrap();
    2521              : 
    2522         1284 :         let tl = uninit_tl.finish_creation().await?;
    2523              :         // The non-test code would call tl.activate() here.
    2524         1284 :         tl.set_state(TimelineState::Active);
    2525         1284 :         Ok(tl)
    2526         1284 :     }
    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          288 :     pub async fn create_test_timeline_with_layers(
    2532          288 :         self: &Arc<Self>,
    2533          288 :         new_timeline_id: TimelineId,
    2534          288 :         initdb_lsn: Lsn,
    2535          288 :         pg_version: u32,
    2536          288 :         ctx: &RequestContext,
    2537          288 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2538          288 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2539          288 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2540          288 :         end_lsn: Lsn,
    2541          288 :     ) -> anyhow::Result<Arc<Timeline>> {
    2542              :         use checks::check_valid_layermap;
    2543              :         use itertools::Itertools;
    2544              : 
    2545          288 :         let tline = self
    2546          288 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2547          288 :             .await?;
    2548          288 :         tline.force_advance_lsn(end_lsn);
    2549          852 :         for deltas in delta_layer_desc {
    2550          564 :             tline
    2551          564 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2552          564 :                 .await?;
    2553              :         }
    2554          696 :         for (lsn, images) in image_layer_desc {
    2555          408 :             tline
    2556          408 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2557          408 :                 .await?;
    2558              :         }
    2559          336 :         for in_memory in in_memory_layer_desc {
    2560           48 :             tline
    2561           48 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2562           48 :                 .await?;
    2563              :         }
    2564          288 :         let layer_names = tline
    2565          288 :             .layers
    2566          288 :             .read()
    2567          288 :             .await
    2568          288 :             .layer_map()
    2569          288 :             .unwrap()
    2570          288 :             .iter_historic_layers()
    2571         1260 :             .map(|layer| layer.layer_name())
    2572          288 :             .collect_vec();
    2573          288 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2574            0 :             bail!("invalid layermap: {err}");
    2575          288 :         }
    2576          288 :         Ok(tline)
    2577          288 :     }
    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<TenantShard>,
    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 [`TenantShard::timelines`] map until the import
    2755              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2756              :     /// [`TenantShard::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<Self>,
    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<TenantShard>,
    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<TenantShard>,
    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 TenantShard::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 TenantShard::shutdown
    2905              :         // already went past shutting down the TenantShard::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 TenantShard::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         4524 :     pub(crate) async fn gc_iteration(
    2969         4524 :         &self,
    2970         4524 :         target_timeline_id: Option<TimelineId>,
    2971         4524 :         horizon: u64,
    2972         4524 :         pitr: Duration,
    2973         4524 :         cancel: &CancellationToken,
    2974         4524 :         ctx: &RequestContext,
    2975         4524 :     ) -> Result<GcResult, GcError> {
    2976         4524 :         // Don't start doing work during shutdown
    2977         4524 :         if let TenantState::Stopping { .. } = self.current_state() {
    2978            0 :             return Ok(GcResult::default());
    2979         4524 :         }
    2980         4524 : 
    2981         4524 :         // there is a global allowed_error for this
    2982         4524 :         if !self.is_active() {
    2983            0 :             return Err(GcError::NotActive);
    2984         4524 :         }
    2985         4524 : 
    2986         4524 :         {
    2987         4524 :             let conf = self.tenant_conf.load();
    2988         4524 : 
    2989         4524 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2990         4524 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2991         4524 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2992         4524 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2993         4524 :             if !conf.location.may_delete_layers_hint() {
    2994            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2995            0 :                 return Ok(GcResult::default());
    2996         4524 :             }
    2997         4524 : 
    2998         4524 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2999         4500 :                 info!("Skipping GC because lsn lease deadline is not reached");
    3000         4500 :                 return Ok(GcResult::default());
    3001           24 :             }
    3002              :         }
    3003              : 
    3004           24 :         let _guard = match self.gc_block.start().await {
    3005           24 :             Ok(guard) => guard,
    3006            0 :             Err(reasons) => {
    3007            0 :                 info!("Skipping GC: {reasons}");
    3008            0 :                 return Ok(GcResult::default());
    3009              :             }
    3010              :         };
    3011              : 
    3012           24 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3013           24 :             .await
    3014         4524 :     }
    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        10488 :     pub fn current_state(&self) -> TenantState {
    3303        10488 :         self.state.borrow().clone()
    3304        10488 :     }
    3305              : 
    3306         5916 :     pub fn is_active(&self) -> bool {
    3307         5916 :         self.current_state() == TenantState::Active
    3308         5916 :     }
    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           36 :     async fn shutdown(
    3413           36 :         &self,
    3414           36 :         shutdown_progress: completion::Barrier,
    3415           36 :         shutdown_mode: timeline::ShutdownMode,
    3416           36 :     ) -> Result<(), completion::Barrier> {
    3417           36 :         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           36 :         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           36 :             shutdown_mode
    3448              :         };
    3449              : 
    3450           36 :         match self.set_stopping(shutdown_progress).await {
    3451           36 :             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           36 :         let mut js = tokio::task::JoinSet::new();
    3463           36 :         {
    3464           36 :             let timelines = self.timelines.lock().unwrap();
    3465           36 :             timelines.values().for_each(|timeline| {
    3466           36 :                 let timeline = Arc::clone(timeline);
    3467           36 :                 let timeline_id = timeline.timeline_id;
    3468           36 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3469           36 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3470           36 :             });
    3471           36 :         }
    3472           36 :         {
    3473           36 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3474           36 :             timelines_offloaded.values().for_each(|timeline| {
    3475            0 :                 timeline.defuse_for_tenant_drop();
    3476           36 :             });
    3477           36 :         }
    3478           36 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3479           36 :         tracing::info!("Waiting for timelines...");
    3480           72 :         while let Some(res) = js.join_next().await {
    3481            0 :             match res {
    3482           36 :                 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           36 :         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           36 :         }
    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           36 :         tracing::debug!("Cancelling CancellationToken");
    3504           36 :         self.cancel.cancel();
    3505           36 : 
    3506           36 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3507           36 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3508           36 :         //
    3509           36 :         // this will additionally shutdown and await all timeline tasks.
    3510           36 :         tracing::debug!("Waiting for tasks...");
    3511           36 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3512              : 
    3513           36 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3514           36 :             walredo_mgr.shutdown().await;
    3515            0 :         }
    3516              : 
    3517              :         // Wait for any in-flight operations to complete
    3518           36 :         self.gate.close().await;
    3519              : 
    3520           36 :         remove_tenant_metrics(&self.tenant_shard_id);
    3521           36 : 
    3522           36 :         Ok(())
    3523           36 :     }
    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           36 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3531           36 :         let mut rx = self.state.subscribe();
    3532           36 : 
    3533           36 :         // cannot stop before we're done activating, so wait out until we're done activating
    3534           36 :         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           36 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3540           36 :         })
    3541           36 :         .await
    3542           36 :         .expect("cannot drop self.state while on a &self method");
    3543           36 : 
    3544           36 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3545           36 :         let mut err = None;
    3546           36 :         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           36 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3555           36 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3556           36 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3557           36 :                 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           36 :         });
    3578           36 :         match (stopping, err) {
    3579           36 :             (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           36 :         let timelines_accessor = self.timelines.lock().unwrap();
    3590           36 :         let not_broken_timelines = timelines_accessor
    3591           36 :             .values()
    3592           36 :             .filter(|timeline| !timeline.is_broken());
    3593           72 :         for timeline in not_broken_timelines {
    3594           36 :             timeline.set_state(TimelineState::Stopping);
    3595           36 :         }
    3596           36 :         Ok(())
    3597           36 :     }
    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         1404 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3745         1404 :         self.shard_identity.stripe_size
    3746         1404 :     }
    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         1392 : fn tree_sort_timelines<T, E>(
    3889         1392 :     timelines: HashMap<TimelineId, T>,
    3890         1392 :     extractor: E,
    3891         1392 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3892         1392 : where
    3893         1392 :     E: Fn(&T) -> Option<TimelineId>,
    3894         1392 : {
    3895         1392 :     let mut result = Vec::with_capacity(timelines.len());
    3896         1392 : 
    3897         1392 :     let mut now = Vec::with_capacity(timelines.len());
    3898         1392 :     // (ancestor, children)
    3899         1392 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3900         1392 :         HashMap::with_capacity(timelines.len());
    3901              : 
    3902         1428 :     for (timeline_id, value) in timelines {
    3903           36 :         if let Some(ancestor_id) = extractor(&value) {
    3904           12 :             let children = later.entry(ancestor_id).or_default();
    3905           12 :             children.push((timeline_id, value));
    3906           24 :         } else {
    3907           24 :             now.push((timeline_id, value));
    3908           24 :         }
    3909              :     }
    3910              : 
    3911         1428 :     while let Some((timeline_id, metadata)) = now.pop() {
    3912           36 :         result.push((timeline_id, metadata));
    3913              :         // All children of this can be loaded now
    3914           36 :         if let Some(mut children) = later.remove(&timeline_id) {
    3915           12 :             now.append(&mut children);
    3916           24 :         }
    3917              :     }
    3918              : 
    3919              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3920         1392 :     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         1392 :     }
    3930         1392 : 
    3931         1392 :     Ok(result)
    3932         1392 : }
    3933              : 
    3934              : enum ActivateTimelineArgs {
    3935              :     Yes {
    3936              :         broker_client: storage_broker::BrokerClientChannel,
    3937              :     },
    3938              :     No,
    3939              : }
    3940              : 
    3941              : impl TenantShard {
    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           24 :     pub fn get_gc_horizon(&self) -> u64 {
    4008           24 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4009           24 :         tenant_conf
    4010           24 :             .gc_horizon
    4011           24 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4012           24 :     }
    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           24 :     pub fn get_pitr_interval(&self) -> Duration {
    4029           24 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4030           24 :         tenant_conf
    4031           24 :             .pitr_interval
    4032           24 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4033           24 :     }
    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           24 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4055           24 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4056           24 :         tenant_conf
    4057           24 :             .lsn_lease_length
    4058           24 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4059           24 :     }
    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         1404 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4073         1404 :         // Collect the offloaded timelines, and sort them for deterministic output.
    4074         1404 :         let offloaded_timelines = self
    4075         1404 :             .timelines_offloaded
    4076         1404 :             .lock()
    4077         1404 :             .unwrap()
    4078         1404 :             .values()
    4079         1404 :             .map(|tli| tli.manifest())
    4080         1404 :             .sorted_by_key(|m| m.timeline_id)
    4081         1404 :             .collect_vec();
    4082         1404 : 
    4083         1404 :         TenantManifest {
    4084         1404 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4085         1404 :             stripe_size: Some(self.get_shard_stripe_size()),
    4086         1404 :             offloaded_timelines,
    4087         1404 :         }
    4088         1404 :     }
    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 [`TenantShard::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         1392 :     fn get_pagestream_throttle_config(
    4143         1392 :         psconf: &'static PageServerConf,
    4144         1392 :         overrides: &pageserver_api::models::TenantConfig,
    4145         1392 :     ) -> throttle::Config {
    4146         1392 :         overrides
    4147         1392 :             .timeline_get_throttle
    4148         1392 :             .clone()
    4149         1392 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4150         1392 :     }
    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         2784 :     fn create_timeline_struct(
    4168         2784 :         &self,
    4169         2784 :         new_timeline_id: TimelineId,
    4170         2784 :         new_metadata: &TimelineMetadata,
    4171         2784 :         previous_heatmap: Option<PreviousHeatmap>,
    4172         2784 :         ancestor: Option<Arc<Timeline>>,
    4173         2784 :         resources: TimelineResources,
    4174         2784 :         cause: CreateTimelineCause,
    4175         2784 :         create_idempotency: CreateTimelineIdempotency,
    4176         2784 :         gc_compaction_state: Option<GcCompactionState>,
    4177         2784 :         rel_size_v2_status: Option<RelSizeMigration>,
    4178         2784 :         ctx: &RequestContext,
    4179         2784 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4180         2784 :         let state = match cause {
    4181              :             CreateTimelineCause::Load => {
    4182         2784 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4183         2784 :                 anyhow::ensure!(
    4184         2784 :                     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         2784 :                 TimelineState::Loading
    4188              :             }
    4189            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4190              :         };
    4191              : 
    4192         2784 :         let pg_version = new_metadata.pg_version();
    4193         2784 : 
    4194         2784 :         let timeline = Timeline::new(
    4195         2784 :             self.conf,
    4196         2784 :             Arc::clone(&self.tenant_conf),
    4197         2784 :             new_metadata,
    4198         2784 :             previous_heatmap,
    4199         2784 :             ancestor,
    4200         2784 :             new_timeline_id,
    4201         2784 :             self.tenant_shard_id,
    4202         2784 :             self.generation,
    4203         2784 :             self.shard_identity,
    4204         2784 :             self.walredo_mgr.clone(),
    4205         2784 :             resources,
    4206         2784 :             pg_version,
    4207         2784 :             state,
    4208         2784 :             self.attach_wal_lag_cooldown.clone(),
    4209         2784 :             create_idempotency,
    4210         2784 :             gc_compaction_state,
    4211         2784 :             rel_size_v2_status,
    4212         2784 :             self.cancel.child_token(),
    4213         2784 :         );
    4214         2784 : 
    4215         2784 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4216         2784 :             .scope(context::Scope::new_timeline(&timeline))
    4217         2784 :             .detached_child();
    4218         2784 : 
    4219         2784 :         Ok((timeline, timeline_ctx))
    4220         2784 :     }
    4221              : 
    4222              :     /// [`TenantShard::shutdown`] must be called before dropping the returned [`TenantShard`] 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         1392 :     fn new(
    4229         1392 :         state: TenantState,
    4230         1392 :         conf: &'static PageServerConf,
    4231         1392 :         attached_conf: AttachedTenantConf,
    4232         1392 :         shard_identity: ShardIdentity,
    4233         1392 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4234         1392 :         tenant_shard_id: TenantShardId,
    4235         1392 :         remote_storage: GenericRemoteStorage,
    4236         1392 :         deletion_queue_client: DeletionQueueClient,
    4237         1392 :         l0_flush_global_state: L0FlushGlobalState,
    4238         1392 :     ) -> TenantShard {
    4239         1392 :         debug_assert!(
    4240         1392 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4241              :         );
    4242              : 
    4243         1392 :         let (state, mut rx) = watch::channel(state);
    4244         1392 : 
    4245         1392 :         tokio::spawn(async move {
    4246         1387 :             // reflect tenant state in metrics:
    4247         1387 :             // - global per tenant state: TENANT_STATE_METRIC
    4248         1387 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4249         1387 :             //
    4250         1387 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4251         1387 :             // alerting.
    4252         1387 : 
    4253         1387 :             let tid = tenant_shard_id.to_string();
    4254         1387 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4255         1387 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4256              : 
    4257         2774 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4258         2774 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4259         2774 :             }
    4260              : 
    4261         1387 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4262         1387 : 
    4263         1387 :             let is_broken = tuple.1;
    4264         1387 :             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         1387 :                 false
    4271              :             };
    4272              : 
    4273              :             loop {
    4274         2774 :                 let labels = &tuple.0;
    4275         2774 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4276         2774 :                 current.inc();
    4277         2774 : 
    4278         2774 :                 if rx.changed().await.is_err() {
    4279              :                     // tenant has been dropped
    4280           84 :                     current.dec();
    4281           84 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4282           84 :                     break;
    4283         1387 :                 }
    4284         1387 : 
    4285         1387 :                 current.dec();
    4286         1387 :                 tuple = inspect_state(&rx.borrow_and_update());
    4287         1387 : 
    4288         1387 :                 let is_broken = tuple.1;
    4289         1387 :                 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         1387 :                 }
    4295              :             }
    4296         1392 :         });
    4297         1392 : 
    4298         1392 :         TenantShard {
    4299         1392 :             tenant_shard_id,
    4300         1392 :             shard_identity,
    4301         1392 :             generation: attached_conf.location.generation,
    4302         1392 :             conf,
    4303         1392 :             // using now here is good enough approximation to catch tenants with really long
    4304         1392 :             // activation times.
    4305         1392 :             constructed_at: Instant::now(),
    4306         1392 :             timelines: Mutex::new(HashMap::new()),
    4307         1392 :             timelines_creating: Mutex::new(HashSet::new()),
    4308         1392 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4309         1392 :             remote_tenant_manifest: Default::default(),
    4310         1392 :             gc_cs: tokio::sync::Mutex::new(()),
    4311         1392 :             walredo_mgr,
    4312         1392 :             remote_storage,
    4313         1392 :             deletion_queue_client,
    4314         1392 :             state,
    4315         1392 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4316         1392 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4317         1392 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4318         1392 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4319         1392 :                 format!("compaction-{tenant_shard_id}"),
    4320         1392 :                 5,
    4321         1392 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4322         1392 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4323         1392 :                 // use an extremely long backoff.
    4324         1392 :                 Some(Duration::from_secs(3600 * 24)),
    4325         1392 :             )),
    4326         1392 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4327         1392 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4328         1392 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4329         1392 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4330         1392 :             cancel: CancellationToken::default(),
    4331         1392 :             gate: Gate::default(),
    4332         1392 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4333         1392 :                 TenantShard::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4334         1392 :             )),
    4335         1392 :             pagestream_throttle_metrics: Arc::new(
    4336         1392 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4337         1392 :             ),
    4338         1392 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4339         1392 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4340         1392 :             gc_block: Default::default(),
    4341         1392 :             l0_flush_global_state,
    4342         1392 :         }
    4343         1392 :     }
    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           24 :     async fn gc_iteration_internal(
    4444           24 :         &self,
    4445           24 :         target_timeline_id: Option<TimelineId>,
    4446           24 :         horizon: u64,
    4447           24 :         pitr: Duration,
    4448           24 :         cancel: &CancellationToken,
    4449           24 :         ctx: &RequestContext,
    4450           24 :     ) -> Result<GcResult, GcError> {
    4451           24 :         let mut totals: GcResult = Default::default();
    4452           24 :         let now = Instant::now();
    4453              : 
    4454           24 :         let gc_timelines = self
    4455           24 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4456           24 :             .await?;
    4457              : 
    4458           24 :         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           24 :         if !gc_timelines.is_empty() {
    4462           24 :             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 `TenantShard::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 [`TenantShard::branch_timeline`] for more information about why branch
    4474              :         // creation task can run concurrently with timeline's GC iteration.
    4475           48 :         for timeline in gc_timelines {
    4476           24 :             if cancel.is_cancelled() {
    4477              :                 // We were requested to shut down. Stop and return with the progress we
    4478              :                 // made.
    4479            0 :                 break;
    4480           24 :             }
    4481           24 :             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           24 :                 r => r?,
    4493              :             };
    4494           24 :             totals += result;
    4495              :         }
    4496              : 
    4497           24 :         totals.elapsed = now.elapsed();
    4498           24 :         Ok(totals)
    4499           24 :     }
    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              :     /// [`TenantShard::get_gc_horizon`].
    4504              :     ///
    4505              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4506           24 :     pub(crate) async fn refresh_gc_info(
    4507           24 :         &self,
    4508           24 :         cancel: &CancellationToken,
    4509           24 :         ctx: &RequestContext,
    4510           24 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4511           24 :         // since this method can now be called at different rates than the configured gc loop, it
    4512           24 :         // might be that these configuration values get applied faster than what it was previously,
    4513           24 :         // since these were only read from the gc task.
    4514           24 :         let horizon = self.get_gc_horizon();
    4515           24 :         let pitr = self.get_pitr_interval();
    4516           24 : 
    4517           24 :         // refresh all timelines
    4518           24 :         let target_timeline_id = None;
    4519           24 : 
    4520           24 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4521           24 :             .await
    4522           24 :     }
    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           48 :     async fn refresh_gc_info_internal(
    4600           48 :         &self,
    4601           48 :         target_timeline_id: Option<TimelineId>,
    4602           48 :         horizon: u64,
    4603           48 :         pitr: Duration,
    4604           48 :         cancel: &CancellationToken,
    4605           48 :         ctx: &RequestContext,
    4606           48 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4607           48 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4608           48 :         // currently visible timelines.
    4609           48 :         let timelines = self
    4610           48 :             .timelines
    4611           48 :             .lock()
    4612           48 :             .unwrap()
    4613           48 :             .values()
    4614          120 :             .filter(|tl| match target_timeline_id.as_ref() {
    4615           24 :                 Some(target) => &tl.timeline_id == target,
    4616           96 :                 None => true,
    4617          120 :             })
    4618           48 :             .cloned()
    4619           48 :             .collect::<Vec<_>>();
    4620           48 : 
    4621           48 :         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           48 :         }
    4625           48 : 
    4626           48 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4627           48 :             HashMap::with_capacity(timelines.len());
    4628           48 : 
    4629           48 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4630           48 :         let now_ts_for_pitr_calc = SystemTime::now();
    4631          120 :         for timeline in timelines.iter() {
    4632          120 :             let ctx = &ctx.with_scope_timeline(timeline);
    4633          120 :             let cutoff = timeline
    4634          120 :                 .get_last_record_lsn()
    4635          120 :                 .checked_sub(horizon)
    4636          120 :                 .unwrap_or(Lsn(0));
    4637              : 
    4638          120 :             let cutoffs = timeline
    4639          120 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4640          120 :                 .await?;
    4641          120 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4642          120 :             assert!(old.is_none());
    4643              :         }
    4644              : 
    4645           48 :         if !self.is_active() || self.cancel.is_cancelled() {
    4646            0 :             return Err(GcError::TenantCancelled);
    4647           48 :         }
    4648              : 
    4649              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4650              :         // because that will stall branch creation.
    4651           48 :         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           48 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4656          168 :         for timeline in timelines {
    4657              :             // We filtered the timeline list above
    4658          120 :             if let Some(target_timeline_id) = target_timeline_id {
    4659           24 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4660           96 :             }
    4661              : 
    4662              :             {
    4663          120 :                 let mut target = timeline.gc_info.write().unwrap();
    4664          120 : 
    4665          120 :                 // Cull any expired leases
    4666          120 :                 let now = SystemTime::now();
    4667          120 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4668          120 : 
    4669          120 :                 timeline
    4670          120 :                     .metrics
    4671          120 :                     .valid_lsn_lease_count_gauge
    4672          120 :                     .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          120 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4676           72 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4677           72 :                         target.within_ancestor_pitr =
    4678           72 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4679           72 :                     }
    4680           48 :                 }
    4681              : 
    4682              :                 // Update metrics that depend on GC state
    4683          120 :                 timeline
    4684          120 :                     .metrics
    4685          120 :                     .archival_size
    4686          120 :                     .set(if target.within_ancestor_pitr {
    4687            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4688              :                     } else {
    4689          120 :                         0
    4690              :                     });
    4691          120 :                 timeline.metrics.pitr_history_size.set(
    4692          120 :                     timeline
    4693          120 :                         .get_last_record_lsn()
    4694          120 :                         .checked_sub(target.cutoffs.time)
    4695          120 :                         .unwrap_or(Lsn(0))
    4696          120 :                         .0,
    4697          120 :                 );
    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          120 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4703          120 :                     let original_cutoffs = target.cutoffs.clone();
    4704          120 :                     // GC cutoffs should never go back
    4705          120 :                     target.cutoffs = GcCutoffs {
    4706          120 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4707          120 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4708          120 :                     }
    4709            0 :                 }
    4710              :             }
    4711              : 
    4712          120 :             gc_timelines.push(timeline);
    4713              :         }
    4714           48 :         drop(gc_cs);
    4715           48 :         Ok(gc_timelines)
    4716           48 :     }
    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         1428 :     async fn branch_timeline_test(
    4724         1428 :         self: &Arc<Self>,
    4725         1428 :         src_timeline: &Arc<Timeline>,
    4726         1428 :         dst_id: TimelineId,
    4727         1428 :         ancestor_lsn: Option<Lsn>,
    4728         1428 :         ctx: &RequestContext,
    4729         1428 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4730         1428 :         let tl = self
    4731         1428 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4732         1428 :             .await?
    4733         1404 :             .into_timeline_for_test();
    4734         1404 :         tl.set_state(TimelineState::Active);
    4735         1404 :         Ok(tl)
    4736         1428 :     }
    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           72 :     pub async fn branch_timeline_test_with_layers(
    4742           72 :         self: &Arc<Self>,
    4743           72 :         src_timeline: &Arc<Timeline>,
    4744           72 :         dst_id: TimelineId,
    4745           72 :         ancestor_lsn: Option<Lsn>,
    4746           72 :         ctx: &RequestContext,
    4747           72 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4748           72 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4749           72 :         end_lsn: Lsn,
    4750           72 :     ) -> anyhow::Result<Arc<Timeline>> {
    4751              :         use checks::check_valid_layermap;
    4752              :         use itertools::Itertools;
    4753              : 
    4754           72 :         let tline = self
    4755           72 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4756           72 :             .await?;
    4757           72 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4758           72 :             ancestor_lsn
    4759              :         } else {
    4760            0 :             tline.get_last_record_lsn()
    4761              :         };
    4762           72 :         assert!(end_lsn >= ancestor_lsn);
    4763           72 :         tline.force_advance_lsn(end_lsn);
    4764          108 :         for deltas in delta_layer_desc {
    4765           36 :             tline
    4766           36 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4767           36 :                 .await?;
    4768              :         }
    4769           96 :         for (lsn, images) in image_layer_desc {
    4770           24 :             tline
    4771           24 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4772           24 :                 .await?;
    4773              :         }
    4774           72 :         let layer_names = tline
    4775           72 :             .layers
    4776           72 :             .read()
    4777           72 :             .await
    4778           72 :             .layer_map()
    4779           72 :             .unwrap()
    4780           72 :             .iter_historic_layers()
    4781           72 :             .map(|layer| layer.layer_name())
    4782           72 :             .collect_vec();
    4783           72 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4784            0 :             bail!("invalid layermap: {err}");
    4785           72 :         }
    4786           72 :         Ok(tline)
    4787           72 :     }
    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         1428 :     async fn branch_timeline_impl(
    4802         1428 :         self: &Arc<Self>,
    4803         1428 :         src_timeline: &Arc<Timeline>,
    4804         1428 :         dst_id: TimelineId,
    4805         1428 :         start_lsn: Option<Lsn>,
    4806         1428 :         ctx: &RequestContext,
    4807         1428 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4808         1428 :         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         1428 :         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         1428 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4817           12 :             let lsn = src_timeline.get_last_record_lsn();
    4818           12 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4819           12 :             lsn
    4820         1428 :         });
    4821              : 
    4822              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4823         1428 :         let timeline_create_guard = match self
    4824         1428 :             .start_creating_timeline(
    4825         1428 :                 dst_id,
    4826         1428 :                 CreateTimelineIdempotency::Branch {
    4827         1428 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4828         1428 :                     ancestor_start_lsn: start_lsn,
    4829         1428 :                 },
    4830         1428 :             )
    4831         1428 :             .await?
    4832              :         {
    4833         1428 :             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         1428 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    4852         1428 :         {
    4853         1428 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4854         1428 :             let planned_cutoff = gc_info.min_cutoff();
    4855         1428 :             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         1428 :                 src_timeline
    4862         1428 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    4863         1428 :                     .context(format!(
    4864         1428 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    4865         1428 :                         *applied_gc_cutoff_lsn,
    4866         1428 :                     ))
    4867         1428 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    4868              : 
    4869              :                 // and then the planned GC cutoff
    4870         1404 :                 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         1404 :                 }
    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         1404 :             last: src_last,
    4888         1404 :             prev: src_prev,
    4889         1404 :         } = src_timeline.get_last_record_rlsn();
    4890         1404 :         let dst_prev = if src_last == start_lsn {
    4891         1296 :             Some(src_prev)
    4892              :         } else {
    4893          108 :             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         1404 :         let metadata = TimelineMetadata::new(
    4900         1404 :             start_lsn,
    4901         1404 :             dst_prev,
    4902         1404 :             Some(src_id),
    4903         1404 :             start_lsn,
    4904         1404 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4905         1404 :             src_timeline.initdb_lsn,
    4906         1404 :             src_timeline.pg_version,
    4907         1404 :         );
    4908              : 
    4909         1404 :         let (uninitialized_timeline, _timeline_ctx) = self
    4910         1404 :             .prepare_new_timeline(
    4911         1404 :                 dst_id,
    4912         1404 :                 &metadata,
    4913         1404 :                 timeline_create_guard,
    4914         1404 :                 start_lsn + 1,
    4915         1404 :                 Some(Arc::clone(src_timeline)),
    4916         1404 :                 Some(src_timeline.get_rel_size_v2_status()),
    4917         1404 :                 ctx,
    4918         1404 :             )
    4919         1404 :             .await?;
    4920              : 
    4921         1404 :         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         1404 :         new_timeline
    4929         1404 :             .remote_client
    4930         1404 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4931         1404 :             .context("branch initial metadata upload")?;
    4932              : 
    4933              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4934              : 
    4935         1404 :         Ok(CreateTimelineResult::Created(new_timeline))
    4936         1428 :     }
    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           12 :             .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         2784 :     async fn start_creating_timeline(
    4964         2784 :         self: &Arc<Self>,
    4965         2784 :         new_timeline_id: TimelineId,
    4966         2784 :         idempotency: CreateTimelineIdempotency,
    4967         2784 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4968         2784 :         let allow_offloaded = false;
    4969         2784 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4970         2772 :             Ok(create_guard) => {
    4971         2772 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4972         2772 :                 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           12 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4991           12 :                 arg,
    4992           12 :             }) => {
    4993           12 :                 {
    4994           12 :                     let existing = &existing.create_idempotency;
    4995           12 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4996           12 :                     debug!("timeline already exists");
    4997              : 
    4998           12 :                     match (existing, &arg) {
    4999              :                         // FailWithConflict => no idempotency check
    5000              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5001              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5002           12 :                             warn!("timeline already exists, failing request");
    5003           12 :                             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         2784 :     }
    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           12 :     async fn bootstrap_timeline(
    5076           12 :         self: &Arc<Self>,
    5077           12 :         timeline_id: TimelineId,
    5078           12 :         pg_version: u32,
    5079           12 :         load_existing_initdb: Option<TimelineId>,
    5080           12 :         ctx: &RequestContext,
    5081           12 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5082           12 :         let timeline_create_guard = match self
    5083           12 :             .start_creating_timeline(
    5084           12 :                 timeline_id,
    5085           12 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5086           12 :             )
    5087           12 :             .await?
    5088              :         {
    5089           12 :             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           12 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5099           12 :         let pgdata_path = path_with_suffix_extension(
    5100           12 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5101           12 :             TEMP_FILE_SUFFIX,
    5102           12 :         );
    5103           12 : 
    5104           12 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5105           12 :         // we won't race with other creations or existent timelines with the same path.
    5106           12 :         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           12 :         }
    5112              : 
    5113              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5114           12 :         let pgdata_path_deferred = pgdata_path.clone();
    5115           12 :         scopeguard::defer! {
    5116           12 :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5117           12 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5118           12 :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5119           12 :             } else {
    5120           12 :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5121           12 :             }
    5122           12 :         }
    5123           12 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5124           12 :             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           12 :             }
    5138           12 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5139           12 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5140           12 :                     self.conf,
    5141           12 :                     &self.remote_storage,
    5142           12 :                     &self.tenant_shard_id,
    5143           12 :                     &existing_initdb_timeline_id,
    5144           12 :                     &self.cancel,
    5145           12 :                 )
    5146           12 :                 .await
    5147           12 :                 .context("download initdb tar")?;
    5148              : 
    5149           12 :             scopeguard::defer! {
    5150           12 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5151           12 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5152           12 :                 }
    5153           12 :             }
    5154           12 : 
    5155           12 :             let buf_read =
    5156           12 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5157           12 :             extract_zst_tarball(&pgdata_path, buf_read)
    5158           12 :                 .await
    5159           12 :                 .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           12 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5173           12 : 
    5174           12 :         // Import the contents of the data directory at the initial checkpoint
    5175           12 :         // LSN, and any WAL after that.
    5176           12 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5177           12 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5178           12 :         let new_metadata = TimelineMetadata::new(
    5179           12 :             Lsn(0),
    5180           12 :             None,
    5181           12 :             None,
    5182           12 :             Lsn(0),
    5183           12 :             pgdata_lsn,
    5184           12 :             pgdata_lsn,
    5185           12 :             pg_version,
    5186           12 :         );
    5187           12 :         let (mut raw_timeline, timeline_ctx) = self
    5188           12 :             .prepare_new_timeline(
    5189           12 :                 timeline_id,
    5190           12 :                 &new_metadata,
    5191           12 :                 timeline_create_guard,
    5192           12 :                 pgdata_lsn,
    5193           12 :                 None,
    5194           12 :                 None,
    5195           12 :                 ctx,
    5196           12 :             )
    5197           12 :             .await?;
    5198              : 
    5199           12 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5200           12 :         raw_timeline
    5201           12 :             .write(|unfinished_timeline| async move {
    5202           12 :                 import_datadir::import_timeline_from_postgres_datadir(
    5203           12 :                     &unfinished_timeline,
    5204           12 :                     &pgdata_path,
    5205           12 :                     pgdata_lsn,
    5206           12 :                     &timeline_ctx,
    5207           12 :                 )
    5208           12 :                 .await
    5209           12 :                 .with_context(|| {
    5210            0 :                     format!(
    5211            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5212            0 :                     )
    5213           12 :                 })?;
    5214              : 
    5215           12 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5216            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5217            0 :                         "failpoint before-checkpoint-new-timeline"
    5218            0 :                     )))
    5219           12 :                 });
    5220              : 
    5221           12 :                 Ok(())
    5222           24 :             })
    5223           12 :             .await?;
    5224              : 
    5225              :         // All done!
    5226           12 :         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           12 :         Ok(CreateTimelineResult::Created(timeline))
    5231           12 :     }
    5232              : 
    5233         2748 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5234         2748 :         RemoteTimelineClient::new(
    5235         2748 :             self.remote_storage.clone(),
    5236         2748 :             self.deletion_queue_client.clone(),
    5237         2748 :             self.conf,
    5238         2748 :             self.tenant_shard_id,
    5239         2748 :             timeline_id,
    5240         2748 :             self.generation,
    5241         2748 :             &self.tenant_conf.load().location,
    5242         2748 :         )
    5243         2748 :     }
    5244              : 
    5245              :     /// Builds required resources for a new timeline.
    5246         2748 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5247         2748 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5248         2748 :         self.get_timeline_resources_for(remote_client)
    5249         2748 :     }
    5250              : 
    5251              :     /// Builds timeline resources for the given remote client.
    5252         2784 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5253         2784 :         TimelineResources {
    5254         2784 :             remote_client,
    5255         2784 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5256         2784 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5257         2784 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5258         2784 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5259         2784 :         }
    5260         2784 :     }
    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         2748 :     async fn prepare_new_timeline<'a>(
    5269         2748 :         &'a self,
    5270         2748 :         new_timeline_id: TimelineId,
    5271         2748 :         new_metadata: &TimelineMetadata,
    5272         2748 :         create_guard: TimelineCreateGuard,
    5273         2748 :         start_lsn: Lsn,
    5274         2748 :         ancestor: Option<Arc<Timeline>>,
    5275         2748 :         rel_size_v2_status: Option<RelSizeMigration>,
    5276         2748 :         ctx: &RequestContext,
    5277         2748 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5278         2748 :         let tenant_shard_id = self.tenant_shard_id;
    5279         2748 : 
    5280         2748 :         let resources = self.build_timeline_resources(new_timeline_id);
    5281         2748 :         resources
    5282         2748 :             .remote_client
    5283         2748 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5284              : 
    5285         2748 :         let (timeline_struct, timeline_ctx) = self
    5286         2748 :             .create_timeline_struct(
    5287         2748 :                 new_timeline_id,
    5288         2748 :                 new_metadata,
    5289         2748 :                 None,
    5290         2748 :                 ancestor,
    5291         2748 :                 resources,
    5292         2748 :                 CreateTimelineCause::Load,
    5293         2748 :                 create_guard.idempotency.clone(),
    5294         2748 :                 None,
    5295         2748 :                 rel_size_v2_status,
    5296         2748 :                 ctx,
    5297         2748 :             )
    5298         2748 :             .context("Failed to create timeline data structure")?;
    5299              : 
    5300         2748 :         timeline_struct.init_empty_layer_map(start_lsn);
    5301              : 
    5302         2748 :         if let Err(e) = self
    5303         2748 :             .create_timeline_files(&create_guard.timeline_path)
    5304         2748 :             .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         2748 :         }
    5312         2748 : 
    5313         2748 :         debug!(
    5314            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5315              :         );
    5316              : 
    5317         2748 :         Ok((
    5318         2748 :             UninitializedTimeline::new(
    5319         2748 :                 self,
    5320         2748 :                 new_timeline_id,
    5321         2748 :                 Some((timeline_struct, create_guard)),
    5322         2748 :             ),
    5323         2748 :             timeline_ctx,
    5324         2748 :         ))
    5325         2748 :     }
    5326              : 
    5327         2748 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5328         2748 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5329              : 
    5330         2748 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5331            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5332         2748 :         });
    5333              : 
    5334         2748 :         Ok(())
    5335         2748 :     }
    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         2784 :     fn create_timeline_create_guard(
    5343         2784 :         self: &Arc<Self>,
    5344         2784 :         timeline_id: TimelineId,
    5345         2784 :         idempotency: CreateTimelineIdempotency,
    5346         2784 :         allow_offloaded: bool,
    5347         2784 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5348         2784 :         let tenant_shard_id = self.tenant_shard_id;
    5349         2784 : 
    5350         2784 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5351              : 
    5352         2784 :         let create_guard = TimelineCreateGuard::new(
    5353         2784 :             self,
    5354         2784 :             timeline_id,
    5355         2784 :             timeline_path.clone(),
    5356         2784 :             idempotency,
    5357         2784 :             allow_offloaded,
    5358         2784 :         )?;
    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         2772 :         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         2772 :         }
    5373         2772 : 
    5374         2772 :         Ok(create_guard)
    5375         2784 :     }
    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 TenantShard 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 TenantShard 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 `TenantShard` 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         1404 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5547              :         // Multiple tasks may call this function concurrently after mutating the TenantShard 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         1404 :         let mut guard = tokio::select! {
    5552         1404 :             guard = self.remote_tenant_manifest.lock() => guard,
    5553         1404 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5554              :         };
    5555              : 
    5556              :         // Build a new manifest.
    5557         1404 :         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         1404 :         if let Some(old) = guard.as_ref() {
    5562           48 :             if manifest.eq_ignoring_version(old) {
    5563           36 :                 return Ok(());
    5564           12 :             }
    5565         1356 :         }
    5566              : 
    5567              :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5568         1368 :         match backoff::retry(
    5569         1368 :             || async {
    5570         1368 :                 upload_tenant_manifest(
    5571         1368 :                     &self.remote_storage,
    5572         1368 :                     &self.tenant_shard_id,
    5573         1368 :                     self.generation,
    5574         1368 :                     &manifest,
    5575         1368 :                     &self.cancel,
    5576         1368 :                 )
    5577         1368 :                 .await
    5578         2736 :             },
    5579         1368 :             |_| self.cancel.is_cancelled(),
    5580         1368 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5581         1368 :             FAILED_REMOTE_OP_RETRIES,
    5582         1368 :             "uploading tenant manifest",
    5583         1368 :             &self.cancel,
    5584         1368 :         )
    5585         1368 :         .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         1368 :                 *guard = Some(manifest);
    5594         1368 : 
    5595         1368 :                 Ok(())
    5596              :             }
    5597              :         }
    5598         1404 :     }
    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     30172700 :     pub fn test_img(s: &str) -> Bytes {
    5705     30172700 :         let mut buf = BytesMut::new();
    5706     30172700 :         buf.extend_from_slice(s.as_bytes());
    5707     30172700 :         buf.resize(64, 0);
    5708     30172700 : 
    5709     30172700 :         buf.freeze()
    5710     30172700 :     }
    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         1536 :     pub(crate) fn setup_logging() {
    5726         1536 :         LOG_HANDLE.get_or_init(|| {
    5727         1464 :             logging::init(
    5728         1464 :                 logging::LogFormat::Test,
    5729         1464 :                 // enable it in case the tests exercise code paths that use
    5730         1464 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5731         1464 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5732         1464 :                 logging::Output::Stdout,
    5733         1464 :             )
    5734         1464 :             .expect("Failed to init test logging");
    5735         1536 :         });
    5736         1536 :     }
    5737              : 
    5738              :     impl TenantHarness {
    5739         1392 :         pub async fn create_custom(
    5740         1392 :             test_name: &'static str,
    5741         1392 :             tenant_conf: pageserver_api::models::TenantConfig,
    5742         1392 :             tenant_id: TenantId,
    5743         1392 :             shard_identity: ShardIdentity,
    5744         1392 :             generation: Generation,
    5745         1392 :         ) -> anyhow::Result<Self> {
    5746         1392 :             setup_logging();
    5747         1392 : 
    5748         1392 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5749         1392 :             let _ = fs::remove_dir_all(&repo_dir);
    5750         1392 :             fs::create_dir_all(&repo_dir)?;
    5751              : 
    5752         1392 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5753         1392 :             // Make a static copy of the config. This can never be free'd, but that's
    5754         1392 :             // OK in a test.
    5755         1392 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5756         1392 : 
    5757         1392 :             let shard = shard_identity.shard_index();
    5758         1392 :             let tenant_shard_id = TenantShardId {
    5759         1392 :                 tenant_id,
    5760         1392 :                 shard_number: shard.shard_number,
    5761         1392 :                 shard_count: shard.shard_count,
    5762         1392 :             };
    5763         1392 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5764         1392 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5765              : 
    5766              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5767         1392 :             let remote_fs_dir = conf.workdir.join("localfs");
    5768         1392 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5769         1392 :             let config = RemoteStorageConfig {
    5770         1392 :                 storage: RemoteStorageKind::LocalFs {
    5771         1392 :                     local_path: remote_fs_dir.clone(),
    5772         1392 :                 },
    5773         1392 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5774         1392 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5775         1392 :             };
    5776         1392 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5777         1392 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5778         1392 : 
    5779         1392 :             Ok(Self {
    5780         1392 :                 conf,
    5781         1392 :                 tenant_conf,
    5782         1392 :                 tenant_shard_id,
    5783         1392 :                 generation,
    5784         1392 :                 shard,
    5785         1392 :                 remote_storage,
    5786         1392 :                 remote_fs_dir,
    5787         1392 :                 deletion_queue,
    5788         1392 :             })
    5789         1392 :         }
    5790              : 
    5791         1308 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5792         1308 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5793         1308 :             // The tests perform them manually if needed.
    5794         1308 :             let tenant_conf = pageserver_api::models::TenantConfig {
    5795         1308 :                 gc_period: Some(Duration::ZERO),
    5796         1308 :                 compaction_period: Some(Duration::ZERO),
    5797         1308 :                 ..Default::default()
    5798         1308 :             };
    5799         1308 :             let tenant_id = TenantId::generate();
    5800         1308 :             let shard = ShardIdentity::unsharded();
    5801         1308 :             Self::create_custom(
    5802         1308 :                 test_name,
    5803         1308 :                 tenant_conf,
    5804         1308 :                 tenant_id,
    5805         1308 :                 shard,
    5806         1308 :                 Generation::new(0xdeadbeef),
    5807         1308 :             )
    5808         1308 :             .await
    5809         1308 :         }
    5810              : 
    5811          120 :         pub fn span(&self) -> tracing::Span {
    5812          120 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5813          120 :         }
    5814              : 
    5815         1392 :         pub(crate) async fn load(&self) -> (Arc<TenantShard>, RequestContext) {
    5816         1392 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    5817         1392 :                 .with_scope_unit_test();
    5818         1392 :             (
    5819         1392 :                 self.do_try_load(&ctx)
    5820         1392 :                     .await
    5821         1392 :                     .expect("failed to load test tenant"),
    5822         1392 :                 ctx,
    5823         1392 :             )
    5824         1392 :         }
    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<TenantShard>> {
    5831              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5832              : 
    5833              :             let tenant = Arc::new(TenantShard::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           12 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5865           12 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5866           12 :         }
    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       321288 :         pub async fn request_redo(
    5877       321288 :             &self,
    5878       321288 :             key: Key,
    5879       321288 :             lsn: Lsn,
    5880       321288 :             base_img: Option<(Lsn, Bytes)>,
    5881       321288 :             records: Vec<(Lsn, NeonWalRecord)>,
    5882       321288 :             _pg_version: u32,
    5883       321288 :             _redo_attempt_type: RedoAttemptType,
    5884       321288 :         ) -> Result<Bytes, walredo::Error> {
    5885     16842120 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5886       321288 :             if records_neon {
    5887              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5888       321288 :                 let mut page = match (base_img, records.first()) {
    5889       156348 :                     (Some((_lsn, img)), _) => {
    5890       156348 :                         let mut page = BytesMut::new();
    5891       156348 :                         page.extend_from_slice(&img);
    5892       156348 :                         page
    5893              :                     }
    5894       164940 :                     (_, 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     17163396 :                 for (record_lsn, record) in records {
    5901     16842120 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5902              :                 }
    5903       321276 :                 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       321288 :         }
    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          108 :         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       384000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    5993              :             use bytes::BufMut;
    5994              : 
    5995       384000 :             let mut crnt_lsn = lsn;
    5996       384000 :             let mut got_base = false;
    5997       384000 : 
    5998       384000 :             let mut acc = Vec::new();
    5999              : 
    6000     33982452 :             while crnt_lsn >= self.start_lsn {
    6001     33982452 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6002     17054064 :                     acc.push(value.clone());
    6003              : 
    6004     16834572 :                     match value {
    6005     16834572 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6006     16834572 :                             if *will_init {
    6007       164508 :                                 got_base = true;
    6008       164508 :                                 break;
    6009     16670064 :                             }
    6010              :                         }
    6011              :                         Value::Image(_) => {
    6012       219492 :                             got_base = true;
    6013       219492 :                             break;
    6014              :                         }
    6015            0 :                         _ => unreachable!(),
    6016              :                     }
    6017     16928388 :                 }
    6018              : 
    6019     33598452 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6020              :             }
    6021              : 
    6022       384000 :             assert!(
    6023       384000 :                 got_base,
    6024            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6025              :             );
    6026              : 
    6027       384000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6028              : 
    6029       384000 :             let mut blob = BytesMut::new();
    6030     17054064 :             for value in acc.into_iter().rev() {
    6031     16834572 :                 match value {
    6032     16834572 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6033     16834572 :                         blob.extend_from_slice(append.as_bytes());
    6034     16834572 :                     }
    6035       219492 :                     Value::Image(img) => {
    6036       219492 :                         blob.put(img);
    6037       219492 :                     }
    6038            0 :                     _ => unreachable!(),
    6039              :                 }
    6040              :             }
    6041              : 
    6042       384000 :             blob.into()
    6043       384000 :         }
    6044              :     }
    6045              : 
    6046              :     #[cfg(feature = "testing")]
    6047              :     #[allow(clippy::too_many_arguments)]
    6048           12 :     async fn randomize_timeline(
    6049           12 :         tenant: &Arc<TenantShard>,
    6050           12 :         new_timeline_id: TimelineId,
    6051           12 :         pg_version: u32,
    6052           12 :         spec: TestTimelineSpecification,
    6053           12 :         random: &mut rand::rngs::StdRng,
    6054           12 :         ctx: &RequestContext,
    6055           12 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6056           12 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6057           12 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6058              : 
    6059           24 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6060           24 :             let mut lsn = lsn_range.start;
    6061         2424 :             while lsn < lsn_range.end {
    6062         2400 :                 let mut key = key_range.start;
    6063       252216 :                 while key < key_range.end {
    6064       249816 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6065       249816 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6066       249816 : 
    6067       249816 :                     if gap {
    6068        12216 :                         continue;
    6069       237600 :                     }
    6070              : 
    6071       237600 :                     let record = if will_init {
    6072         2292 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6073              :                     } else {
    6074       235308 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6075              :                     };
    6076              : 
    6077       237600 :                     storage.insert((key, lsn), record);
    6078       237600 : 
    6079       237600 :                     key = key.next();
    6080              :                 }
    6081         2400 :                 lsn = Lsn(lsn.0 + 1);
    6082              :             }
    6083              : 
    6084              :             // Stash some interesting LSN for future use
    6085           72 :             for offset in [0, 5, 100].iter() {
    6086           72 :                 if *offset == 0 {
    6087           24 :                     interesting_lsns.push(lsn_range.start);
    6088           24 :                 } else {
    6089           48 :                     let below = lsn_range.start.checked_sub(*offset);
    6090           48 :                     match below {
    6091           48 :                         Some(v) if v >= spec.start_lsn => {
    6092           48 :                             interesting_lsns.push(v);
    6093           48 :                         }
    6094            0 :                         _ => {}
    6095              :                     }
    6096              : 
    6097           48 :                     let above = Lsn(lsn_range.start.0 + offset);
    6098           48 :                     interesting_lsns.push(above);
    6099              :                 }
    6100              :             }
    6101              :         }
    6102              : 
    6103           36 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6104           36 :             let mut lsn = lsn_range.start;
    6105         3780 :             while lsn < lsn_range.end {
    6106         3744 :                 let mut key = key_range.start;
    6107       133344 :                 while key < key_range.end {
    6108       129600 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6109       129600 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6110       129600 : 
    6111       129600 :                     if gap {
    6112         6048 :                         continue;
    6113       123552 :                     }
    6114              : 
    6115       123552 :                     let record = if will_init {
    6116         1236 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6117              :                     } else {
    6118       122316 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6119              :                     };
    6120              : 
    6121       123552 :                     storage.insert((key, lsn), record);
    6122       123552 : 
    6123       123552 :                     key = key.next();
    6124              :                 }
    6125         3744 :                 lsn = Lsn(lsn.0 + 1);
    6126              :             }
    6127              : 
    6128              :             // Stash some interesting LSN for future use
    6129          108 :             for offset in [0, 5, 100].iter() {
    6130          108 :                 if *offset == 0 {
    6131           36 :                     interesting_lsns.push(lsn_range.start);
    6132           36 :                 } else {
    6133           72 :                     let below = lsn_range.start.checked_sub(*offset);
    6134           72 :                     match below {
    6135           72 :                         Some(v) if v >= spec.start_lsn => {
    6136           36 :                             interesting_lsns.push(v);
    6137           36 :                         }
    6138           36 :                         _ => {}
    6139              :                     }
    6140              : 
    6141           72 :                     let above = Lsn(lsn_range.start.0 + offset);
    6142           72 :                     interesting_lsns.push(above);
    6143              :                 }
    6144              :             }
    6145              :         }
    6146              : 
    6147           36 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6148           36 :             let mut key = key_range.start;
    6149         1704 :             while key < key_range.end {
    6150         1668 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6151         1668 :                 let record = Value::Image(blob.clone());
    6152         1668 :                 storage.insert((key, *lsn), record);
    6153         1668 : 
    6154         1668 :                 key = key.next();
    6155         1668 :             }
    6156              : 
    6157              :             // Stash some interesting LSN for future use
    6158          108 :             for offset in [0, 5, 100].iter() {
    6159          108 :                 if *offset == 0 {
    6160           36 :                     interesting_lsns.push(*lsn);
    6161           36 :                 } else {
    6162           72 :                     let below = lsn.checked_sub(*offset);
    6163           72 :                     match below {
    6164           72 :                         Some(v) if v >= spec.start_lsn => {
    6165           48 :                             interesting_lsns.push(v);
    6166           48 :                         }
    6167           24 :                         _ => {}
    6168              :                     }
    6169              : 
    6170           72 :                     let above = Lsn(lsn.0 + offset);
    6171           72 :                     interesting_lsns.push(above);
    6172              :                 }
    6173              :             }
    6174              :         }
    6175              : 
    6176           12 :         let in_memory_test_layers = {
    6177           12 :             let mut acc = Vec::new();
    6178              : 
    6179           24 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6180           24 :                 let mut data = Vec::new();
    6181           24 : 
    6182           24 :                 let mut lsn = lsn_range.start;
    6183         2424 :                 while lsn < lsn_range.end {
    6184         2400 :                     let mut key = key_range.start;
    6185       240000 :                     while key < key_range.end {
    6186       237600 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6187       237600 :                             data.push((key, lsn, record.clone()));
    6188       237600 :                         }
    6189              : 
    6190       237600 :                         key = key.next();
    6191              :                     }
    6192         2400 :                     lsn = Lsn(lsn.0 + 1);
    6193              :                 }
    6194              : 
    6195           24 :                 acc.push(InMemoryLayerTestDesc {
    6196           24 :                     data,
    6197           24 :                     lsn_range: lsn_range.clone(),
    6198           24 :                     is_open: false,
    6199           24 :                 })
    6200              :             }
    6201              : 
    6202           12 :             acc
    6203              :         };
    6204              : 
    6205           12 :         let delta_test_layers = {
    6206           12 :             let mut acc = Vec::new();
    6207              : 
    6208           36 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6209           36 :                 let mut data = Vec::new();
    6210           36 : 
    6211           36 :                 let mut lsn = lsn_range.start;
    6212         3780 :                 while lsn < lsn_range.end {
    6213         3744 :                     let mut key = key_range.start;
    6214       127296 :                     while key < key_range.end {
    6215       123552 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6216       123552 :                             data.push((key, lsn, record.clone()));
    6217       123552 :                         }
    6218              : 
    6219       123552 :                         key = key.next();
    6220              :                     }
    6221         3744 :                     lsn = Lsn(lsn.0 + 1);
    6222              :                 }
    6223              : 
    6224           36 :                 acc.push(DeltaLayerTestDesc {
    6225           36 :                     data,
    6226           36 :                     lsn_range: lsn_range.clone(),
    6227           36 :                     key_range: key_range.clone(),
    6228           36 :                 })
    6229              :             }
    6230              : 
    6231           12 :             acc
    6232              :         };
    6233              : 
    6234           12 :         let image_test_layers = {
    6235           12 :             let mut acc = Vec::new();
    6236              : 
    6237           36 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6238           36 :                 let mut data = Vec::new();
    6239           36 : 
    6240           36 :                 let mut key = key_range.start;
    6241         1704 :                 while key < key_range.end {
    6242         1668 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6243         1668 :                         let blob = match record {
    6244         1668 :                             Value::Image(blob) => blob.clone(),
    6245            0 :                             _ => unreachable!(),
    6246              :                         };
    6247              : 
    6248         1668 :                         data.push((key, blob));
    6249            0 :                     }
    6250              : 
    6251         1668 :                     key = key.next();
    6252              :                 }
    6253              : 
    6254           36 :                 acc.push((*lsn, data));
    6255              :             }
    6256              : 
    6257           12 :             acc
    6258              :         };
    6259              : 
    6260           12 :         let tline = tenant
    6261           12 :             .create_test_timeline_with_layers(
    6262           12 :                 new_timeline_id,
    6263           12 :                 spec.start_lsn,
    6264           12 :                 pg_version,
    6265           12 :                 ctx,
    6266           12 :                 in_memory_test_layers,
    6267           12 :                 delta_test_layers,
    6268           12 :                 image_test_layers,
    6269           12 :                 spec.last_record_lsn,
    6270           12 :             )
    6271           12 :             .await?;
    6272              : 
    6273           12 :         Ok((
    6274           12 :             tline,
    6275           12 :             Storage {
    6276           12 :                 storage,
    6277           12 :                 start_lsn: spec.start_lsn,
    6278           12 :             },
    6279           12 :             interesting_lsns,
    6280           12 :         ))
    6281           12 :     }
    6282              : 
    6283              :     #[tokio::test]
    6284           12 :     async fn test_basic() -> anyhow::Result<()> {
    6285           12 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6286           12 :         let tline = tenant
    6287           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6288           12 :             .await?;
    6289           12 : 
    6290           12 :         let mut writer = tline.writer().await;
    6291           12 :         writer
    6292           12 :             .put(
    6293           12 :                 *TEST_KEY,
    6294           12 :                 Lsn(0x10),
    6295           12 :                 &Value::Image(test_img("foo at 0x10")),
    6296           12 :                 &ctx,
    6297           12 :             )
    6298           12 :             .await?;
    6299           12 :         writer.finish_write(Lsn(0x10));
    6300           12 :         drop(writer);
    6301           12 : 
    6302           12 :         let mut writer = tline.writer().await;
    6303           12 :         writer
    6304           12 :             .put(
    6305           12 :                 *TEST_KEY,
    6306           12 :                 Lsn(0x20),
    6307           12 :                 &Value::Image(test_img("foo at 0x20")),
    6308           12 :                 &ctx,
    6309           12 :             )
    6310           12 :             .await?;
    6311           12 :         writer.finish_write(Lsn(0x20));
    6312           12 :         drop(writer);
    6313           12 : 
    6314           12 :         assert_eq!(
    6315           12 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6316           12 :             test_img("foo at 0x10")
    6317           12 :         );
    6318           12 :         assert_eq!(
    6319           12 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6320           12 :             test_img("foo at 0x10")
    6321           12 :         );
    6322           12 :         assert_eq!(
    6323           12 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6324           12 :             test_img("foo at 0x20")
    6325           12 :         );
    6326           12 : 
    6327           12 :         Ok(())
    6328           12 :     }
    6329              : 
    6330              :     #[tokio::test]
    6331           12 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6332           12 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6333           12 :             .await?
    6334           12 :             .load()
    6335           12 :             .await;
    6336           12 :         let _ = tenant
    6337           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6338           12 :             .await?;
    6339           12 : 
    6340           12 :         match tenant
    6341           12 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6342           12 :             .await
    6343           12 :         {
    6344           12 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6345           12 :             Err(e) => assert_eq!(
    6346           12 :                 e.to_string(),
    6347           12 :                 "timeline already exists with different parameters".to_string()
    6348           12 :             ),
    6349           12 :         }
    6350           12 : 
    6351           12 :         Ok(())
    6352           12 :     }
    6353              : 
    6354              :     /// Convenience function to create a page image with given string as the only content
    6355           60 :     pub fn test_value(s: &str) -> Value {
    6356           60 :         let mut buf = BytesMut::new();
    6357           60 :         buf.extend_from_slice(s.as_bytes());
    6358           60 :         Value::Image(buf.freeze())
    6359           60 :     }
    6360              : 
    6361              :     ///
    6362              :     /// Test branch creation
    6363              :     ///
    6364              :     #[tokio::test]
    6365           12 :     async fn test_branch() -> anyhow::Result<()> {
    6366           12 :         use std::str::from_utf8;
    6367           12 : 
    6368           12 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6369           12 :         let tline = tenant
    6370           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6371           12 :             .await?;
    6372           12 :         let mut writer = tline.writer().await;
    6373           12 : 
    6374           12 :         #[allow(non_snake_case)]
    6375           12 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6376           12 :         #[allow(non_snake_case)]
    6377           12 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6378           12 : 
    6379           12 :         // Insert a value on the timeline
    6380           12 :         writer
    6381           12 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6382           12 :             .await?;
    6383           12 :         writer
    6384           12 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6385           12 :             .await?;
    6386           12 :         writer.finish_write(Lsn(0x20));
    6387           12 : 
    6388           12 :         writer
    6389           12 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6390           12 :             .await?;
    6391           12 :         writer.finish_write(Lsn(0x30));
    6392           12 :         writer
    6393           12 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6394           12 :             .await?;
    6395           12 :         writer.finish_write(Lsn(0x40));
    6396           12 : 
    6397           12 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6398           12 : 
    6399           12 :         // Branch the history, modify relation differently on the new timeline
    6400           12 :         tenant
    6401           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6402           12 :             .await?;
    6403           12 :         let newtline = tenant
    6404           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6405           12 :             .expect("Should have a local timeline");
    6406           12 :         let mut new_writer = newtline.writer().await;
    6407           12 :         new_writer
    6408           12 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6409           12 :             .await?;
    6410           12 :         new_writer.finish_write(Lsn(0x40));
    6411           12 : 
    6412           12 :         // Check page contents on both branches
    6413           12 :         assert_eq!(
    6414           12 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6415           12 :             "foo at 0x40"
    6416           12 :         );
    6417           12 :         assert_eq!(
    6418           12 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6419           12 :             "bar at 0x40"
    6420           12 :         );
    6421           12 :         assert_eq!(
    6422           12 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6423           12 :             "foobar at 0x20"
    6424           12 :         );
    6425           12 : 
    6426           12 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6427           12 : 
    6428           12 :         Ok(())
    6429           12 :     }
    6430              : 
    6431          120 :     async fn make_some_layers(
    6432          120 :         tline: &Timeline,
    6433          120 :         start_lsn: Lsn,
    6434          120 :         ctx: &RequestContext,
    6435          120 :     ) -> anyhow::Result<()> {
    6436          120 :         let mut lsn = start_lsn;
    6437              :         {
    6438          120 :             let mut writer = tline.writer().await;
    6439              :             // Create a relation on the timeline
    6440          120 :             writer
    6441          120 :                 .put(
    6442          120 :                     *TEST_KEY,
    6443          120 :                     lsn,
    6444          120 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6445          120 :                     ctx,
    6446          120 :                 )
    6447          120 :                 .await?;
    6448          120 :             writer.finish_write(lsn);
    6449          120 :             lsn += 0x10;
    6450          120 :             writer
    6451          120 :                 .put(
    6452          120 :                     *TEST_KEY,
    6453          120 :                     lsn,
    6454          120 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6455          120 :                     ctx,
    6456          120 :                 )
    6457          120 :                 .await?;
    6458          120 :             writer.finish_write(lsn);
    6459          120 :             lsn += 0x10;
    6460          120 :         }
    6461          120 :         tline.freeze_and_flush().await?;
    6462              :         {
    6463          120 :             let mut writer = tline.writer().await;
    6464          120 :             writer
    6465          120 :                 .put(
    6466          120 :                     *TEST_KEY,
    6467          120 :                     lsn,
    6468          120 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6469          120 :                     ctx,
    6470          120 :                 )
    6471          120 :                 .await?;
    6472          120 :             writer.finish_write(lsn);
    6473          120 :             lsn += 0x10;
    6474          120 :             writer
    6475          120 :                 .put(
    6476          120 :                     *TEST_KEY,
    6477          120 :                     lsn,
    6478          120 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6479          120 :                     ctx,
    6480          120 :                 )
    6481          120 :                 .await?;
    6482          120 :             writer.finish_write(lsn);
    6483          120 :         }
    6484          120 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6485          120 :     }
    6486              : 
    6487              :     #[tokio::test(start_paused = true)]
    6488           12 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6489           12 :         let (tenant, ctx) =
    6490           12 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6491           12 :                 .await?
    6492           12 :                 .load()
    6493           12 :                 .await;
    6494           12 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6495           12 :         // initial transition into AttachedSingle.
    6496           12 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6497           12 :         tokio::time::resume();
    6498           12 :         let tline = tenant
    6499           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6500           12 :             .await?;
    6501           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6502           12 : 
    6503           12 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6504           12 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6505           12 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6506           12 :         // below should fail.
    6507           12 :         tenant
    6508           12 :             .gc_iteration(
    6509           12 :                 Some(TIMELINE_ID),
    6510           12 :                 0x10,
    6511           12 :                 Duration::ZERO,
    6512           12 :                 &CancellationToken::new(),
    6513           12 :                 &ctx,
    6514           12 :             )
    6515           12 :             .await?;
    6516           12 : 
    6517           12 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6518           12 :         match tenant
    6519           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6520           12 :             .await
    6521           12 :         {
    6522           12 :             Ok(_) => panic!("branching should have failed"),
    6523           12 :             Err(err) => {
    6524           12 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6525           12 :                     panic!("wrong error type")
    6526           12 :                 };
    6527           12 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6528           12 :                 assert!(
    6529           12 :                     err.source()
    6530           12 :                         .unwrap()
    6531           12 :                         .to_string()
    6532           12 :                         .contains("we might've already garbage collected needed data")
    6533           12 :                 )
    6534           12 :             }
    6535           12 :         }
    6536           12 : 
    6537           12 :         Ok(())
    6538           12 :     }
    6539              : 
    6540              :     #[tokio::test]
    6541           12 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6542           12 :         let (tenant, ctx) =
    6543           12 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6544           12 :                 .await?
    6545           12 :                 .load()
    6546           12 :                 .await;
    6547           12 : 
    6548           12 :         let tline = tenant
    6549           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6550           12 :             .await?;
    6551           12 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6552           12 :         match tenant
    6553           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6554           12 :             .await
    6555           12 :         {
    6556           12 :             Ok(_) => panic!("branching should have failed"),
    6557           12 :             Err(err) => {
    6558           12 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6559           12 :                     panic!("wrong error type");
    6560           12 :                 };
    6561           12 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6562           12 :                 assert!(
    6563           12 :                     &err.source()
    6564           12 :                         .unwrap()
    6565           12 :                         .to_string()
    6566           12 :                         .contains("is earlier than latest GC cutoff")
    6567           12 :                 );
    6568           12 :             }
    6569           12 :         }
    6570           12 : 
    6571           12 :         Ok(())
    6572           12 :     }
    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           12 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6599           12 :         let (tenant, ctx) =
    6600           12 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6601           12 :                 .await?
    6602           12 :                 .load()
    6603           12 :                 .await;
    6604           12 :         let tline = tenant
    6605           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6606           12 :             .await?;
    6607           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6608           12 : 
    6609           12 :         tenant
    6610           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6611           12 :             .await?;
    6612           12 :         let newtline = tenant
    6613           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6614           12 :             .expect("Should have a local timeline");
    6615           12 : 
    6616           12 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6617           12 : 
    6618           12 :         tline.set_broken("test".to_owned());
    6619           12 : 
    6620           12 :         tenant
    6621           12 :             .gc_iteration(
    6622           12 :                 Some(TIMELINE_ID),
    6623           12 :                 0x10,
    6624           12 :                 Duration::ZERO,
    6625           12 :                 &CancellationToken::new(),
    6626           12 :                 &ctx,
    6627           12 :             )
    6628           12 :             .await?;
    6629           12 : 
    6630           12 :         // The branchpoints should contain all timelines, even ones marked
    6631           12 :         // as Broken.
    6632           12 :         {
    6633           12 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6634           12 :             assert_eq!(branchpoints.len(), 1);
    6635           12 :             assert_eq!(
    6636           12 :                 branchpoints[0],
    6637           12 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6638           12 :             );
    6639           12 :         }
    6640           12 : 
    6641           12 :         // You can read the key from the child branch even though the parent is
    6642           12 :         // Broken, as long as you don't need to access data from the parent.
    6643           12 :         assert_eq!(
    6644           12 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6645           12 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6646           12 :         );
    6647           12 : 
    6648           12 :         // This needs to traverse to the parent, and fails.
    6649           12 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6650           12 :         assert!(
    6651           12 :             err.to_string().starts_with(&format!(
    6652           12 :                 "bad state on timeline {}: Broken",
    6653           12 :                 tline.timeline_id
    6654           12 :             )),
    6655           12 :             "{err}"
    6656           12 :         );
    6657           12 : 
    6658           12 :         Ok(())
    6659           12 :     }
    6660              : 
    6661              :     #[tokio::test]
    6662           12 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6663           12 :         let (tenant, ctx) =
    6664           12 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6665           12 :                 .await?
    6666           12 :                 .load()
    6667           12 :                 .await;
    6668           12 :         let tline = tenant
    6669           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6670           12 :             .await?;
    6671           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6672           12 : 
    6673           12 :         tenant
    6674           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6675           12 :             .await?;
    6676           12 :         let newtline = tenant
    6677           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6678           12 :             .expect("Should have a local timeline");
    6679           12 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6680           12 :         tenant
    6681           12 :             .gc_iteration(
    6682           12 :                 Some(TIMELINE_ID),
    6683           12 :                 0x10,
    6684           12 :                 Duration::ZERO,
    6685           12 :                 &CancellationToken::new(),
    6686           12 :                 &ctx,
    6687           12 :             )
    6688           12 :             .await?;
    6689           12 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6690           12 : 
    6691           12 :         Ok(())
    6692           12 :     }
    6693              :     #[tokio::test]
    6694           12 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6695           12 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6696           12 :             .await?
    6697           12 :             .load()
    6698           12 :             .await;
    6699           12 :         let tline = tenant
    6700           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6701           12 :             .await?;
    6702           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6703           12 : 
    6704           12 :         tenant
    6705           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6706           12 :             .await?;
    6707           12 :         let newtline = tenant
    6708           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6709           12 :             .expect("Should have a local timeline");
    6710           12 : 
    6711           12 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6712           12 : 
    6713           12 :         // run gc on parent
    6714           12 :         tenant
    6715           12 :             .gc_iteration(
    6716           12 :                 Some(TIMELINE_ID),
    6717           12 :                 0x10,
    6718           12 :                 Duration::ZERO,
    6719           12 :                 &CancellationToken::new(),
    6720           12 :                 &ctx,
    6721           12 :             )
    6722           12 :             .await?;
    6723           12 : 
    6724           12 :         // Check that the data is still accessible on the branch.
    6725           12 :         assert_eq!(
    6726           12 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6727           12 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6728           12 :         );
    6729           12 : 
    6730           12 :         Ok(())
    6731           12 :     }
    6732              : 
    6733              :     #[tokio::test]
    6734           12 :     async fn timeline_load() -> anyhow::Result<()> {
    6735           12 :         const TEST_NAME: &str = "timeline_load";
    6736           12 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6737           12 :         {
    6738           12 :             let (tenant, ctx) = harness.load().await;
    6739           12 :             let tline = tenant
    6740           12 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6741           12 :                 .await?;
    6742           12 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6743           12 :             // so that all uploads finish & we can call harness.load() below again
    6744           12 :             tenant
    6745           12 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6746           12 :                 .instrument(harness.span())
    6747           12 :                 .await
    6748           12 :                 .ok()
    6749           12 :                 .unwrap();
    6750           12 :         }
    6751           12 : 
    6752           12 :         let (tenant, _ctx) = harness.load().await;
    6753           12 :         tenant
    6754           12 :             .get_timeline(TIMELINE_ID, true)
    6755           12 :             .expect("cannot load timeline");
    6756           12 : 
    6757           12 :         Ok(())
    6758           12 :     }
    6759              : 
    6760              :     #[tokio::test]
    6761           12 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6762           12 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6763           12 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6764           12 :         // create two timelines
    6765           12 :         {
    6766           12 :             let (tenant, ctx) = harness.load().await;
    6767           12 :             let tline = tenant
    6768           12 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6769           12 :                 .await?;
    6770           12 : 
    6771           12 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6772           12 : 
    6773           12 :             let child_tline = tenant
    6774           12 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6775           12 :                 .await?;
    6776           12 :             child_tline.set_state(TimelineState::Active);
    6777           12 : 
    6778           12 :             let newtline = tenant
    6779           12 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6780           12 :                 .expect("Should have a local timeline");
    6781           12 : 
    6782           12 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6783           12 : 
    6784           12 :             // so that all uploads finish & we can call harness.load() below again
    6785           12 :             tenant
    6786           12 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6787           12 :                 .instrument(harness.span())
    6788           12 :                 .await
    6789           12 :                 .ok()
    6790           12 :                 .unwrap();
    6791           12 :         }
    6792           12 : 
    6793           12 :         // check that both of them are initially unloaded
    6794           12 :         let (tenant, _ctx) = harness.load().await;
    6795           12 : 
    6796           12 :         // check that both, child and ancestor are loaded
    6797           12 :         let _child_tline = tenant
    6798           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6799           12 :             .expect("cannot get child timeline loaded");
    6800           12 : 
    6801           12 :         let _ancestor_tline = tenant
    6802           12 :             .get_timeline(TIMELINE_ID, true)
    6803           12 :             .expect("cannot get ancestor timeline loaded");
    6804           12 : 
    6805           12 :         Ok(())
    6806           12 :     }
    6807              : 
    6808              :     #[tokio::test]
    6809           12 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6810           12 :         use storage_layer::AsLayerDesc;
    6811           12 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6812           12 :             .await?
    6813           12 :             .load()
    6814           12 :             .await;
    6815           12 :         let tline = tenant
    6816           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6817           12 :             .await?;
    6818           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6819           12 : 
    6820           12 :         let layer_map = tline.layers.read().await;
    6821           12 :         let level0_deltas = layer_map
    6822           12 :             .layer_map()?
    6823           12 :             .level0_deltas()
    6824           12 :             .iter()
    6825           24 :             .map(|desc| layer_map.get_from_desc(desc))
    6826           12 :             .collect::<Vec<_>>();
    6827           12 : 
    6828           12 :         assert!(!level0_deltas.is_empty());
    6829           12 : 
    6830           36 :         for delta in level0_deltas {
    6831           12 :             // Ensure we are dumping a delta layer here
    6832           24 :             assert!(delta.layer_desc().is_delta);
    6833           24 :             delta.dump(true, &ctx).await.unwrap();
    6834           12 :         }
    6835           12 : 
    6836           12 :         Ok(())
    6837           12 :     }
    6838              : 
    6839              :     #[tokio::test]
    6840           12 :     async fn test_images() -> anyhow::Result<()> {
    6841           12 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6842           12 :         let tline = tenant
    6843           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6844           12 :             .await?;
    6845           12 : 
    6846           12 :         let mut writer = tline.writer().await;
    6847           12 :         writer
    6848           12 :             .put(
    6849           12 :                 *TEST_KEY,
    6850           12 :                 Lsn(0x10),
    6851           12 :                 &Value::Image(test_img("foo at 0x10")),
    6852           12 :                 &ctx,
    6853           12 :             )
    6854           12 :             .await?;
    6855           12 :         writer.finish_write(Lsn(0x10));
    6856           12 :         drop(writer);
    6857           12 : 
    6858           12 :         tline.freeze_and_flush().await?;
    6859           12 :         tline
    6860           12 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6861           12 :             .await?;
    6862           12 : 
    6863           12 :         let mut writer = tline.writer().await;
    6864           12 :         writer
    6865           12 :             .put(
    6866           12 :                 *TEST_KEY,
    6867           12 :                 Lsn(0x20),
    6868           12 :                 &Value::Image(test_img("foo at 0x20")),
    6869           12 :                 &ctx,
    6870           12 :             )
    6871           12 :             .await?;
    6872           12 :         writer.finish_write(Lsn(0x20));
    6873           12 :         drop(writer);
    6874           12 : 
    6875           12 :         tline.freeze_and_flush().await?;
    6876           12 :         tline
    6877           12 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6878           12 :             .await?;
    6879           12 : 
    6880           12 :         let mut writer = tline.writer().await;
    6881           12 :         writer
    6882           12 :             .put(
    6883           12 :                 *TEST_KEY,
    6884           12 :                 Lsn(0x30),
    6885           12 :                 &Value::Image(test_img("foo at 0x30")),
    6886           12 :                 &ctx,
    6887           12 :             )
    6888           12 :             .await?;
    6889           12 :         writer.finish_write(Lsn(0x30));
    6890           12 :         drop(writer);
    6891           12 : 
    6892           12 :         tline.freeze_and_flush().await?;
    6893           12 :         tline
    6894           12 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6895           12 :             .await?;
    6896           12 : 
    6897           12 :         let mut writer = tline.writer().await;
    6898           12 :         writer
    6899           12 :             .put(
    6900           12 :                 *TEST_KEY,
    6901           12 :                 Lsn(0x40),
    6902           12 :                 &Value::Image(test_img("foo at 0x40")),
    6903           12 :                 &ctx,
    6904           12 :             )
    6905           12 :             .await?;
    6906           12 :         writer.finish_write(Lsn(0x40));
    6907           12 :         drop(writer);
    6908           12 : 
    6909           12 :         tline.freeze_and_flush().await?;
    6910           12 :         tline
    6911           12 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6912           12 :             .await?;
    6913           12 : 
    6914           12 :         assert_eq!(
    6915           12 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6916           12 :             test_img("foo at 0x10")
    6917           12 :         );
    6918           12 :         assert_eq!(
    6919           12 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6920           12 :             test_img("foo at 0x10")
    6921           12 :         );
    6922           12 :         assert_eq!(
    6923           12 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6924           12 :             test_img("foo at 0x20")
    6925           12 :         );
    6926           12 :         assert_eq!(
    6927           12 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6928           12 :             test_img("foo at 0x30")
    6929           12 :         );
    6930           12 :         assert_eq!(
    6931           12 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6932           12 :             test_img("foo at 0x40")
    6933           12 :         );
    6934           12 : 
    6935           12 :         Ok(())
    6936           12 :     }
    6937              : 
    6938           24 :     async fn bulk_insert_compact_gc(
    6939           24 :         tenant: &TenantShard,
    6940           24 :         timeline: &Arc<Timeline>,
    6941           24 :         ctx: &RequestContext,
    6942           24 :         lsn: Lsn,
    6943           24 :         repeat: usize,
    6944           24 :         key_count: usize,
    6945           24 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6946           24 :         let compact = true;
    6947           24 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6948           24 :     }
    6949              : 
    6950           48 :     async fn bulk_insert_maybe_compact_gc(
    6951           48 :         tenant: &TenantShard,
    6952           48 :         timeline: &Arc<Timeline>,
    6953           48 :         ctx: &RequestContext,
    6954           48 :         mut lsn: Lsn,
    6955           48 :         repeat: usize,
    6956           48 :         key_count: usize,
    6957           48 :         compact: bool,
    6958           48 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6959           48 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6960           48 : 
    6961           48 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6962           48 :         let mut blknum = 0;
    6963           48 : 
    6964           48 :         // Enforce that key range is monotonously increasing
    6965           48 :         let mut keyspace = KeySpaceAccum::new();
    6966           48 : 
    6967           48 :         let cancel = CancellationToken::new();
    6968           48 : 
    6969           48 :         for _ in 0..repeat {
    6970         2400 :             for _ in 0..key_count {
    6971     24000000 :                 test_key.field6 = blknum;
    6972     24000000 :                 let mut writer = timeline.writer().await;
    6973     24000000 :                 writer
    6974     24000000 :                     .put(
    6975     24000000 :                         test_key,
    6976     24000000 :                         lsn,
    6977     24000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6978     24000000 :                         ctx,
    6979     24000000 :                     )
    6980     24000000 :                     .await?;
    6981     24000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6982     24000000 :                 writer.finish_write(lsn);
    6983     24000000 :                 drop(writer);
    6984     24000000 : 
    6985     24000000 :                 keyspace.add_key(test_key);
    6986     24000000 : 
    6987     24000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6988     24000000 :                 blknum += 1;
    6989              :             }
    6990              : 
    6991         2400 :             timeline.freeze_and_flush().await?;
    6992         2400 :             if compact {
    6993              :                 // this requires timeline to be &Arc<Timeline>
    6994         1200 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    6995         1200 :             }
    6996              : 
    6997              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6998              :             // originally was.
    6999         2400 :             let res = tenant
    7000         2400 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7001         2400 :                 .await?;
    7002              : 
    7003         2400 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7004              :         }
    7005              : 
    7006           48 :         Ok(inserted)
    7007           48 :     }
    7008              : 
    7009              :     //
    7010              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7011              :     // Repeat 50 times.
    7012              :     //
    7013              :     #[tokio::test]
    7014           12 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7015           12 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7016           12 :         let (tenant, ctx) = harness.load().await;
    7017           12 :         let tline = tenant
    7018           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7019           12 :             .await?;
    7020           12 : 
    7021           12 :         let lsn = Lsn(0x10);
    7022           12 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7023           12 : 
    7024           12 :         Ok(())
    7025           12 :     }
    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           12 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7046           12 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7047           12 :         let (tenant, ctx) = harness.load().await;
    7048           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7049           12 :         let tline = tenant
    7050           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7051           12 :             .await?;
    7052           12 : 
    7053           12 :         let lsn = Lsn(0x10);
    7054           12 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7055           12 : 
    7056           12 :         let guard = tline.layers.read().await;
    7057           12 :         let lm = guard.layer_map()?;
    7058           12 : 
    7059           12 :         lm.dump(true, &ctx).await?;
    7060           12 : 
    7061           12 :         let mut reads = Vec::new();
    7062           12 :         let mut prev = None;
    7063           72 :         lm.iter_historic_layers().for_each(|desc| {
    7064           72 :             if !desc.is_delta() {
    7065           12 :                 prev = Some(desc.clone());
    7066           12 :                 return;
    7067           60 :             }
    7068           60 : 
    7069           60 :             let start = desc.key_range.start;
    7070           60 :             let end = desc
    7071           60 :                 .key_range
    7072           60 :                 .start
    7073           60 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    7074           60 :             reads.push(KeySpace {
    7075           60 :                 ranges: vec![start..end],
    7076           60 :             });
    7077           12 : 
    7078           60 :             if let Some(prev) = &prev {
    7079           60 :                 if !prev.is_delta() {
    7080           60 :                     return;
    7081           12 :                 }
    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           12 :             };
    7097           12 : 
    7098           12 :             prev = Some(desc.clone());
    7099           72 :         });
    7100           12 : 
    7101           12 :         drop(guard);
    7102           12 : 
    7103           12 :         // Pick a big LSN such that we query over all the changes.
    7104           12 :         let reads_lsn = Lsn(u64::MAX - 1);
    7105           12 : 
    7106           72 :         for read in reads {
    7107           60 :             info!("Doing vectored read on {:?}", read);
    7108           12 : 
    7109           60 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7110           12 : 
    7111           60 :             let vectored_res = tline
    7112           60 :                 .get_vectored_impl(
    7113           60 :                     query,
    7114           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7115           60 :                     &ctx,
    7116           60 :                 )
    7117           60 :                 .await;
    7118           12 : 
    7119           60 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7120           60 :             let mut expect_missing = false;
    7121           60 :             let mut key = read.start().unwrap();
    7122         1980 :             while key != read.end().unwrap() {
    7123         1920 :                 if let Some(lsns) = inserted.get(&key) {
    7124         1920 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7125         1920 :                     match expected_lsn {
    7126         1920 :                         Some(lsn) => {
    7127         1920 :                             expected_lsns.insert(key, *lsn);
    7128         1920 :                         }
    7129           12 :                         None => {
    7130           12 :                             expect_missing = true;
    7131            0 :                             break;
    7132           12 :                         }
    7133           12 :                     }
    7134           12 :                 } else {
    7135           12 :                     expect_missing = true;
    7136            0 :                     break;
    7137           12 :                 }
    7138           12 : 
    7139         1920 :                 key = key.next();
    7140           12 :             }
    7141           12 : 
    7142           60 :             if expect_missing {
    7143           12 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7144           12 :             } else {
    7145         1920 :                 for (key, image) in vectored_res? {
    7146         1920 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7147         1920 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7148         1920 :                     assert_eq!(image?, expected_image);
    7149           12 :                 }
    7150           12 :             }
    7151           12 :         }
    7152           12 : 
    7153           12 :         Ok(())
    7154           12 :     }
    7155              : 
    7156              :     #[tokio::test]
    7157           12 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7158           12 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7159           12 : 
    7160           12 :         let (tenant, ctx) = harness.load().await;
    7161           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7162           12 :         let (tline, ctx) = tenant
    7163           12 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7164           12 :             .await?;
    7165           12 :         let tline = tline.raw_timeline().unwrap();
    7166           12 : 
    7167           12 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7168           12 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7169           12 :         modification.set_lsn(Lsn(0x1008))?;
    7170           12 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7171           12 :         modification.commit(&ctx).await?;
    7172           12 : 
    7173           12 :         let child_timeline_id = TimelineId::generate();
    7174           12 :         tenant
    7175           12 :             .branch_timeline_test(
    7176           12 :                 tline,
    7177           12 :                 child_timeline_id,
    7178           12 :                 Some(tline.get_last_record_lsn()),
    7179           12 :                 &ctx,
    7180           12 :             )
    7181           12 :             .await?;
    7182           12 : 
    7183           12 :         let child_timeline = tenant
    7184           12 :             .get_timeline(child_timeline_id, true)
    7185           12 :             .expect("Should have the branched timeline");
    7186           12 : 
    7187           12 :         let aux_keyspace = KeySpace {
    7188           12 :             ranges: vec![NON_INHERITED_RANGE],
    7189           12 :         };
    7190           12 :         let read_lsn = child_timeline.get_last_record_lsn();
    7191           12 : 
    7192           12 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7193           12 : 
    7194           12 :         let vectored_res = child_timeline
    7195           12 :             .get_vectored_impl(
    7196           12 :                 query,
    7197           12 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7198           12 :                 &ctx,
    7199           12 :             )
    7200           12 :             .await;
    7201           12 : 
    7202           12 :         let images = vectored_res?;
    7203           12 :         assert!(images.is_empty());
    7204           12 :         Ok(())
    7205           12 :     }
    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           12 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7226           12 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7227           12 :             // Make compaction deterministic
    7228           12 :             gc_period: Some(Duration::ZERO),
    7229           12 :             compaction_period: Some(Duration::ZERO),
    7230           12 :             // Encourage creation of L1 layers
    7231           12 :             checkpoint_distance: Some(16 * 1024),
    7232           12 :             compaction_target_size: Some(8 * 1024),
    7233           12 :             ..Default::default()
    7234           12 :         };
    7235           12 : 
    7236           12 :         let harness = TenantHarness::create_custom(
    7237           12 :             "test_get_vectored_key_gap",
    7238           12 :             tenant_conf,
    7239           12 :             TenantId::generate(),
    7240           12 :             ShardIdentity::unsharded(),
    7241           12 :             Generation::new(0xdeadbeef),
    7242           12 :         )
    7243           12 :         .await?;
    7244           12 :         let (tenant, ctx) = harness.load().await;
    7245           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7246           12 : 
    7247           12 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7248           12 :         let gap_at_key = current_key.add(100);
    7249           12 :         let mut current_lsn = Lsn(0x10);
    7250           12 : 
    7251           12 :         const KEY_COUNT: usize = 10_000;
    7252           12 : 
    7253           12 :         let timeline_id = TimelineId::generate();
    7254           12 :         let current_timeline = tenant
    7255           12 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7256           12 :             .await?;
    7257           12 : 
    7258           12 :         current_lsn += 0x100;
    7259           12 : 
    7260           12 :         let mut writer = current_timeline.writer().await;
    7261           12 :         writer
    7262           12 :             .put(
    7263           12 :                 gap_at_key,
    7264           12 :                 current_lsn,
    7265           12 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    7266           12 :                 &ctx,
    7267           12 :             )
    7268           12 :             .await?;
    7269           12 :         writer.finish_write(current_lsn);
    7270           12 :         drop(writer);
    7271           12 : 
    7272           12 :         let mut latest_lsns = HashMap::new();
    7273           12 :         latest_lsns.insert(gap_at_key, current_lsn);
    7274           12 : 
    7275           12 :         current_timeline.freeze_and_flush().await?;
    7276           12 : 
    7277           12 :         let child_timeline_id = TimelineId::generate();
    7278           12 : 
    7279           12 :         tenant
    7280           12 :             .branch_timeline_test(
    7281           12 :                 &current_timeline,
    7282           12 :                 child_timeline_id,
    7283           12 :                 Some(current_lsn),
    7284           12 :                 &ctx,
    7285           12 :             )
    7286           12 :             .await?;
    7287           12 :         let child_timeline = tenant
    7288           12 :             .get_timeline(child_timeline_id, true)
    7289           12 :             .expect("Should have the branched timeline");
    7290           12 : 
    7291       120012 :         for i in 0..KEY_COUNT {
    7292       120000 :             if current_key == gap_at_key {
    7293           12 :                 current_key = current_key.next();
    7294           12 :                 continue;
    7295       119988 :             }
    7296       119988 : 
    7297       119988 :             current_lsn += 0x10;
    7298           12 : 
    7299       119988 :             let mut writer = child_timeline.writer().await;
    7300       119988 :             writer
    7301       119988 :                 .put(
    7302       119988 :                     current_key,
    7303       119988 :                     current_lsn,
    7304       119988 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    7305       119988 :                     &ctx,
    7306       119988 :                 )
    7307       119988 :                 .await?;
    7308       119988 :             writer.finish_write(current_lsn);
    7309       119988 :             drop(writer);
    7310       119988 : 
    7311       119988 :             latest_lsns.insert(current_key, current_lsn);
    7312       119988 :             current_key = current_key.next();
    7313       119988 : 
    7314       119988 :             // Flush every now and then to encourage layer file creation.
    7315       119988 :             if i % 500 == 0 {
    7316          240 :                 child_timeline.freeze_and_flush().await?;
    7317       119748 :             }
    7318           12 :         }
    7319           12 : 
    7320           12 :         child_timeline.freeze_and_flush().await?;
    7321           12 :         let mut flags = EnumSet::new();
    7322           12 :         flags.insert(CompactFlags::ForceRepartition);
    7323           12 :         child_timeline
    7324           12 :             .compact(&CancellationToken::new(), flags, &ctx)
    7325           12 :             .await?;
    7326           12 : 
    7327           12 :         let key_near_end = {
    7328           12 :             let mut tmp = current_key;
    7329           12 :             tmp.field6 -= 10;
    7330           12 :             tmp
    7331           12 :         };
    7332           12 : 
    7333           12 :         let key_near_gap = {
    7334           12 :             let mut tmp = gap_at_key;
    7335           12 :             tmp.field6 -= 10;
    7336           12 :             tmp
    7337           12 :         };
    7338           12 : 
    7339           12 :         let read = KeySpace {
    7340           12 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7341           12 :         };
    7342           12 : 
    7343           12 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7344           12 : 
    7345           12 :         let results = child_timeline
    7346           12 :             .get_vectored_impl(
    7347           12 :                 query,
    7348           12 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7349           12 :                 &ctx,
    7350           12 :             )
    7351           12 :             .await?;
    7352           12 : 
    7353          264 :         for (key, img_res) in results {
    7354          252 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7355          252 :             assert_eq!(img_res?, expected);
    7356           12 :         }
    7357           12 : 
    7358           12 :         Ok(())
    7359           12 :     }
    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           12 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7389           12 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7390           12 :         let (tenant, ctx) = harness.load().await;
    7391           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7392           12 : 
    7393           12 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7394           12 :         let end_key = start_key.add(1000);
    7395           12 :         let child_gap_at_key = start_key.add(500);
    7396           12 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7397           12 : 
    7398           12 :         let mut current_lsn = Lsn(0x10);
    7399           12 : 
    7400           12 :         let timeline_id = TimelineId::generate();
    7401           12 :         let parent_timeline = tenant
    7402           12 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7403           12 :             .await?;
    7404           12 : 
    7405           12 :         current_lsn += 0x100;
    7406           12 : 
    7407           48 :         for _ in 0..3 {
    7408           36 :             let mut key = start_key;
    7409        36036 :             while key < end_key {
    7410        36000 :                 current_lsn += 0x10;
    7411        36000 : 
    7412        36000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    7413           12 : 
    7414        36000 :                 let mut writer = parent_timeline.writer().await;
    7415        36000 :                 writer
    7416        36000 :                     .put(
    7417        36000 :                         key,
    7418        36000 :                         current_lsn,
    7419        36000 :                         &Value::Image(test_img(&image_value)),
    7420        36000 :                         &ctx,
    7421        36000 :                     )
    7422        36000 :                     .await?;
    7423        36000 :                 writer.finish_write(current_lsn);
    7424        36000 : 
    7425        36000 :                 if key == child_gap_at_key {
    7426           36 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7427        35964 :                 }
    7428           12 : 
    7429        36000 :                 key = key.next();
    7430           12 :             }
    7431           12 : 
    7432           36 :             parent_timeline.freeze_and_flush().await?;
    7433           12 :         }
    7434           12 : 
    7435           12 :         let child_timeline_id = TimelineId::generate();
    7436           12 : 
    7437           12 :         let child_timeline = tenant
    7438           12 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7439           12 :             .await?;
    7440           12 : 
    7441           12 :         let mut key = start_key;
    7442        12012 :         while key < end_key {
    7443        12000 :             if key == child_gap_at_key {
    7444           12 :                 key = key.next();
    7445           12 :                 continue;
    7446        11988 :             }
    7447        11988 : 
    7448        11988 :             current_lsn += 0x10;
    7449           12 : 
    7450        11988 :             let mut writer = child_timeline.writer().await;
    7451        11988 :             writer
    7452        11988 :                 .put(
    7453        11988 :                     key,
    7454        11988 :                     current_lsn,
    7455        11988 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    7456        11988 :                     &ctx,
    7457        11988 :                 )
    7458        11988 :                 .await?;
    7459        11988 :             writer.finish_write(current_lsn);
    7460        11988 : 
    7461        11988 :             key = key.next();
    7462           12 :         }
    7463           12 : 
    7464           12 :         child_timeline.freeze_and_flush().await?;
    7465           12 : 
    7466           12 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7467           12 :         let mut query_lsns = Vec::new();
    7468           36 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7469          216 :             for offset in lsn_offsets {
    7470          180 :                 query_lsns.push(Lsn(image_lsn
    7471          180 :                     .0
    7472          180 :                     .checked_add_signed(offset)
    7473          180 :                     .expect("Shouldn't overflow")));
    7474          180 :             }
    7475           12 :         }
    7476           12 : 
    7477          192 :         for query_lsn in query_lsns {
    7478          180 :             let query = VersionedKeySpaceQuery::uniform(
    7479          180 :                 KeySpace {
    7480          180 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7481          180 :                 },
    7482          180 :                 query_lsn,
    7483          180 :             );
    7484           12 : 
    7485          180 :             let results = child_timeline
    7486          180 :                 .get_vectored_impl(
    7487          180 :                     query,
    7488          180 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7489          180 :                     &ctx,
    7490          180 :                 )
    7491          180 :                 .await;
    7492           12 : 
    7493          180 :             let expected_item = parent_gap_lsns
    7494          180 :                 .iter()
    7495          180 :                 .rev()
    7496          408 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7497          180 : 
    7498          180 :             info!(
    7499           12 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7500           12 :                 query_lsn, expected_item
    7501           12 :             );
    7502           12 : 
    7503          180 :             match expected_item {
    7504          156 :                 Some((_, img_value)) => {
    7505          156 :                     let key_results = results.expect("No vectored get error expected");
    7506          156 :                     let key_result = &key_results[&child_gap_at_key];
    7507          156 :                     let returned_img = key_result
    7508          156 :                         .as_ref()
    7509          156 :                         .expect("No page reconstruct error expected");
    7510          156 : 
    7511          156 :                     info!(
    7512           12 :                         "Vectored read at LSN {} returned image {}",
    7513            0 :                         query_lsn,
    7514            0 :                         std::str::from_utf8(returned_img)?
    7515           12 :                     );
    7516          156 :                     assert_eq!(*returned_img, test_img(img_value));
    7517           12 :                 }
    7518           12 :                 None => {
    7519           24 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7520           12 :                 }
    7521           12 :             }
    7522           12 :         }
    7523           12 : 
    7524           12 :         Ok(())
    7525           12 :     }
    7526              : 
    7527              :     #[tokio::test]
    7528           12 :     async fn test_random_updates() -> anyhow::Result<()> {
    7529           12 :         let names_algorithms = [
    7530           12 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7531           12 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7532           12 :         ];
    7533           36 :         for (name, algorithm) in names_algorithms {
    7534           24 :             test_random_updates_algorithm(name, algorithm).await?;
    7535           12 :         }
    7536           12 :         Ok(())
    7537           12 :     }
    7538              : 
    7539           24 :     async fn test_random_updates_algorithm(
    7540           24 :         name: &'static str,
    7541           24 :         compaction_algorithm: CompactionAlgorithm,
    7542           24 :     ) -> anyhow::Result<()> {
    7543           24 :         let mut harness = TenantHarness::create(name).await?;
    7544           24 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7545           24 :             kind: compaction_algorithm,
    7546           24 :         });
    7547           24 :         let (tenant, ctx) = harness.load().await;
    7548           24 :         let tline = tenant
    7549           24 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7550           24 :             .await?;
    7551              : 
    7552              :         const NUM_KEYS: usize = 1000;
    7553           24 :         let cancel = CancellationToken::new();
    7554           24 : 
    7555           24 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7556           24 :         let mut test_key_end = test_key;
    7557           24 :         test_key_end.field6 = NUM_KEYS as u32;
    7558           24 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7559           24 : 
    7560           24 :         let mut keyspace = KeySpaceAccum::new();
    7561           24 : 
    7562           24 :         // Track when each page was last modified. Used to assert that
    7563           24 :         // a read sees the latest page version.
    7564           24 :         let mut updated = [Lsn(0); NUM_KEYS];
    7565           24 : 
    7566           24 :         let mut lsn = Lsn(0x10);
    7567              :         #[allow(clippy::needless_range_loop)]
    7568        24024 :         for blknum in 0..NUM_KEYS {
    7569        24000 :             lsn = Lsn(lsn.0 + 0x10);
    7570        24000 :             test_key.field6 = blknum as u32;
    7571        24000 :             let mut writer = tline.writer().await;
    7572        24000 :             writer
    7573        24000 :                 .put(
    7574        24000 :                     test_key,
    7575        24000 :                     lsn,
    7576        24000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7577        24000 :                     &ctx,
    7578        24000 :                 )
    7579        24000 :                 .await?;
    7580        24000 :             writer.finish_write(lsn);
    7581        24000 :             updated[blknum] = lsn;
    7582        24000 :             drop(writer);
    7583        24000 : 
    7584        24000 :             keyspace.add_key(test_key);
    7585              :         }
    7586              : 
    7587         1224 :         for _ in 0..50 {
    7588      1201200 :             for _ in 0..NUM_KEYS {
    7589      1200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7590      1200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7591      1200000 :                 test_key.field6 = blknum as u32;
    7592      1200000 :                 let mut writer = tline.writer().await;
    7593      1200000 :                 writer
    7594      1200000 :                     .put(
    7595      1200000 :                         test_key,
    7596      1200000 :                         lsn,
    7597      1200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7598      1200000 :                         &ctx,
    7599      1200000 :                     )
    7600      1200000 :                     .await?;
    7601      1200000 :                 writer.finish_write(lsn);
    7602      1200000 :                 drop(writer);
    7603      1200000 :                 updated[blknum] = lsn;
    7604              :             }
    7605              : 
    7606              :             // Read all the blocks
    7607      1200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7608      1200000 :                 test_key.field6 = blknum as u32;
    7609      1200000 :                 assert_eq!(
    7610      1200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7611      1200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7612              :                 );
    7613              :             }
    7614              : 
    7615              :             // Perform a cycle of flush, and GC
    7616         1200 :             tline.freeze_and_flush().await?;
    7617         1200 :             tenant
    7618         1200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7619         1200 :                 .await?;
    7620              :         }
    7621              : 
    7622           24 :         Ok(())
    7623           24 :     }
    7624              : 
    7625              :     #[tokio::test]
    7626           12 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7627           12 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7628           12 :             .await?
    7629           12 :             .load()
    7630           12 :             .await;
    7631           12 :         let mut tline = tenant
    7632           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7633           12 :             .await?;
    7634           12 : 
    7635           12 :         const NUM_KEYS: usize = 1000;
    7636           12 : 
    7637           12 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7638           12 : 
    7639           12 :         let mut keyspace = KeySpaceAccum::new();
    7640           12 : 
    7641           12 :         let cancel = CancellationToken::new();
    7642           12 : 
    7643           12 :         // Track when each page was last modified. Used to assert that
    7644           12 :         // a read sees the latest page version.
    7645           12 :         let mut updated = [Lsn(0); NUM_KEYS];
    7646           12 : 
    7647           12 :         let mut lsn = Lsn(0x10);
    7648           12 :         #[allow(clippy::needless_range_loop)]
    7649        12012 :         for blknum in 0..NUM_KEYS {
    7650        12000 :             lsn = Lsn(lsn.0 + 0x10);
    7651        12000 :             test_key.field6 = blknum as u32;
    7652        12000 :             let mut writer = tline.writer().await;
    7653        12000 :             writer
    7654        12000 :                 .put(
    7655        12000 :                     test_key,
    7656        12000 :                     lsn,
    7657        12000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7658        12000 :                     &ctx,
    7659        12000 :                 )
    7660        12000 :                 .await?;
    7661        12000 :             writer.finish_write(lsn);
    7662        12000 :             updated[blknum] = lsn;
    7663        12000 :             drop(writer);
    7664        12000 : 
    7665        12000 :             keyspace.add_key(test_key);
    7666           12 :         }
    7667           12 : 
    7668          612 :         for _ in 0..50 {
    7669          600 :             let new_tline_id = TimelineId::generate();
    7670          600 :             tenant
    7671          600 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7672          600 :                 .await?;
    7673          600 :             tline = tenant
    7674          600 :                 .get_timeline(new_tline_id, true)
    7675          600 :                 .expect("Should have the branched timeline");
    7676           12 : 
    7677       600600 :             for _ in 0..NUM_KEYS {
    7678       600000 :                 lsn = Lsn(lsn.0 + 0x10);
    7679       600000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7680       600000 :                 test_key.field6 = blknum as u32;
    7681       600000 :                 let mut writer = tline.writer().await;
    7682       600000 :                 writer
    7683       600000 :                     .put(
    7684       600000 :                         test_key,
    7685       600000 :                         lsn,
    7686       600000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7687       600000 :                         &ctx,
    7688       600000 :                     )
    7689       600000 :                     .await?;
    7690       600000 :                 println!("updating {} at {}", blknum, lsn);
    7691       600000 :                 writer.finish_write(lsn);
    7692       600000 :                 drop(writer);
    7693       600000 :                 updated[blknum] = lsn;
    7694           12 :             }
    7695           12 : 
    7696           12 :             // Read all the blocks
    7697       600000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7698       600000 :                 test_key.field6 = blknum as u32;
    7699       600000 :                 assert_eq!(
    7700       600000 :                     tline.get(test_key, lsn, &ctx).await?,
    7701       600000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7702           12 :                 );
    7703           12 :             }
    7704           12 : 
    7705           12 :             // Perform a cycle of flush, compact, and GC
    7706          600 :             tline.freeze_and_flush().await?;
    7707          600 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7708          600 :             tenant
    7709          600 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7710          600 :                 .await?;
    7711           12 :         }
    7712           12 : 
    7713           12 :         Ok(())
    7714           12 :     }
    7715              : 
    7716              :     #[tokio::test]
    7717           12 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7718           12 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7719           12 :             .await?
    7720           12 :             .load()
    7721           12 :             .await;
    7722           12 :         let mut tline = tenant
    7723           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7724           12 :             .await?;
    7725           12 : 
    7726           12 :         const NUM_KEYS: usize = 100;
    7727           12 :         const NUM_TLINES: usize = 50;
    7728           12 : 
    7729           12 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7730           12 :         // Track page mutation lsns across different timelines.
    7731           12 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7732           12 : 
    7733           12 :         let mut lsn = Lsn(0x10);
    7734           12 : 
    7735           12 :         #[allow(clippy::needless_range_loop)]
    7736          612 :         for idx in 0..NUM_TLINES {
    7737          600 :             let new_tline_id = TimelineId::generate();
    7738          600 :             tenant
    7739          600 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7740          600 :                 .await?;
    7741          600 :             tline = tenant
    7742          600 :                 .get_timeline(new_tline_id, true)
    7743          600 :                 .expect("Should have the branched timeline");
    7744           12 : 
    7745        60600 :             for _ in 0..NUM_KEYS {
    7746        60000 :                 lsn = Lsn(lsn.0 + 0x10);
    7747        60000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7748        60000 :                 test_key.field6 = blknum as u32;
    7749        60000 :                 let mut writer = tline.writer().await;
    7750        60000 :                 writer
    7751        60000 :                     .put(
    7752        60000 :                         test_key,
    7753        60000 :                         lsn,
    7754        60000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7755        60000 :                         &ctx,
    7756        60000 :                     )
    7757        60000 :                     .await?;
    7758        60000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7759        60000 :                 writer.finish_write(lsn);
    7760        60000 :                 drop(writer);
    7761        60000 :                 updated[idx][blknum] = lsn;
    7762           12 :             }
    7763           12 :         }
    7764           12 : 
    7765           12 :         // Read pages from leaf timeline across all ancestors.
    7766          600 :         for (idx, lsns) in updated.iter().enumerate() {
    7767        60000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7768           12 :                 // Skip empty mutations.
    7769        60000 :                 if lsn.0 == 0 {
    7770        21964 :                     continue;
    7771        38036 :                 }
    7772        38036 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7773        38036 :                 test_key.field6 = blknum as u32;
    7774        38036 :                 assert_eq!(
    7775        38036 :                     tline.get(test_key, *lsn, &ctx).await?,
    7776        38036 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7777           12 :                 );
    7778           12 :             }
    7779           12 :         }
    7780           12 :         Ok(())
    7781           12 :     }
    7782              : 
    7783              :     #[tokio::test]
    7784           12 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7785           12 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7786           12 :             .await?
    7787           12 :             .load()
    7788           12 :             .await;
    7789           12 : 
    7790           12 :         let initdb_lsn = Lsn(0x20);
    7791           12 :         let (utline, ctx) = tenant
    7792           12 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7793           12 :             .await?;
    7794           12 :         let tline = utline.raw_timeline().unwrap();
    7795           12 : 
    7796           12 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7797           12 :         tline.maybe_spawn_flush_loop();
    7798           12 : 
    7799           12 :         // Make sure the timeline has the minimum set of required keys for operation.
    7800           12 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7801           12 :         // Except if you `put` at `initdb_lsn`.
    7802           12 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7803           12 :         // It uses `repartition()`, which assumes some keys to be present.
    7804           12 :         // Let's make sure the test timeline can handle that case.
    7805           12 :         {
    7806           12 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7807           12 :             assert_eq!(
    7808           12 :                 timeline::FlushLoopState::Running {
    7809           12 :                     expect_initdb_optimization: false,
    7810           12 :                     initdb_optimization_count: 0,
    7811           12 :                 },
    7812           12 :                 *state
    7813           12 :             );
    7814           12 :             *state = timeline::FlushLoopState::Running {
    7815           12 :                 expect_initdb_optimization: true,
    7816           12 :                 initdb_optimization_count: 0,
    7817           12 :             };
    7818           12 :         }
    7819           12 : 
    7820           12 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7821           12 :         // As explained above, the optimization requires some keys to be present.
    7822           12 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7823           12 :         // This is what `create_test_timeline` does, by the way.
    7824           12 :         let mut modification = tline.begin_modification(initdb_lsn);
    7825           12 :         modification
    7826           12 :             .init_empty_test_timeline()
    7827           12 :             .context("init_empty_test_timeline")?;
    7828           12 :         modification
    7829           12 :             .commit(&ctx)
    7830           12 :             .await
    7831           12 :             .context("commit init_empty_test_timeline modification")?;
    7832           12 : 
    7833           12 :         // Do the flush. The flush code will check the expectations that we set above.
    7834           12 :         tline.freeze_and_flush().await?;
    7835           12 : 
    7836           12 :         // assert freeze_and_flush exercised the initdb optimization
    7837           12 :         {
    7838           12 :             let state = tline.flush_loop_state.lock().unwrap();
    7839           12 :             let timeline::FlushLoopState::Running {
    7840           12 :                 expect_initdb_optimization,
    7841           12 :                 initdb_optimization_count,
    7842           12 :             } = *state
    7843           12 :             else {
    7844           12 :                 panic!("unexpected state: {:?}", *state);
    7845           12 :             };
    7846           12 :             assert!(expect_initdb_optimization);
    7847           12 :             assert!(initdb_optimization_count > 0);
    7848           12 :         }
    7849           12 :         Ok(())
    7850           12 :     }
    7851              : 
    7852              :     #[tokio::test]
    7853           12 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7854           12 :         let name = "test_create_guard_crash";
    7855           12 :         let harness = TenantHarness::create(name).await?;
    7856           12 :         {
    7857           12 :             let (tenant, ctx) = harness.load().await;
    7858           12 :             let (tline, _ctx) = tenant
    7859           12 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7860           12 :                 .await?;
    7861           12 :             // Leave the timeline ID in [`TenantShard::timelines_creating`] to exclude attempting to create it again
    7862           12 :             let raw_tline = tline.raw_timeline().unwrap();
    7863           12 :             raw_tline
    7864           12 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7865           12 :                 .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           12 :                 .await;
    7867           12 :             std::mem::forget(tline);
    7868           12 :         }
    7869           12 : 
    7870           12 :         let (tenant, _) = harness.load().await;
    7871           12 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7872           12 :             Ok(_) => panic!("timeline should've been removed during load"),
    7873           12 :             Err(e) => {
    7874           12 :                 assert_eq!(
    7875           12 :                     e,
    7876           12 :                     GetTimelineError::NotFound {
    7877           12 :                         tenant_id: tenant.tenant_shard_id,
    7878           12 :                         timeline_id: TIMELINE_ID,
    7879           12 :                     }
    7880           12 :                 )
    7881           12 :             }
    7882           12 :         }
    7883           12 : 
    7884           12 :         assert!(
    7885           12 :             !harness
    7886           12 :                 .conf
    7887           12 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7888           12 :                 .exists()
    7889           12 :         );
    7890           12 : 
    7891           12 :         Ok(())
    7892           12 :     }
    7893              : 
    7894              :     #[tokio::test]
    7895           12 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7896           12 :         let names_algorithms = [
    7897           12 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7898           12 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7899           12 :         ];
    7900           36 :         for (name, algorithm) in names_algorithms {
    7901           24 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7902           12 :         }
    7903           12 :         Ok(())
    7904           12 :     }
    7905              : 
    7906           24 :     async fn test_read_at_max_lsn_algorithm(
    7907           24 :         name: &'static str,
    7908           24 :         compaction_algorithm: CompactionAlgorithm,
    7909           24 :     ) -> anyhow::Result<()> {
    7910           24 :         let mut harness = TenantHarness::create(name).await?;
    7911           24 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7912           24 :             kind: compaction_algorithm,
    7913           24 :         });
    7914           24 :         let (tenant, ctx) = harness.load().await;
    7915           24 :         let tline = tenant
    7916           24 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7917           24 :             .await?;
    7918              : 
    7919           24 :         let lsn = Lsn(0x10);
    7920           24 :         let compact = false;
    7921           24 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7922              : 
    7923           24 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7924           24 :         let read_lsn = Lsn(u64::MAX - 1);
    7925              : 
    7926           24 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7927           24 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7928              : 
    7929           24 :         Ok(())
    7930           24 :     }
    7931              : 
    7932              :     #[tokio::test]
    7933           12 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7934           12 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7935           12 :         let (tenant, ctx) = harness.load().await;
    7936           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7937           12 :         let tline = tenant
    7938           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7939           12 :             .await?;
    7940           12 : 
    7941           12 :         const NUM_KEYS: usize = 1000;
    7942           12 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7943           12 : 
    7944           12 :         let cancel = CancellationToken::new();
    7945           12 : 
    7946           12 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7947           12 :         base_key.field1 = AUX_KEY_PREFIX;
    7948           12 :         let mut test_key = base_key;
    7949           12 : 
    7950           12 :         // Track when each page was last modified. Used to assert that
    7951           12 :         // a read sees the latest page version.
    7952           12 :         let mut updated = [Lsn(0); NUM_KEYS];
    7953           12 : 
    7954           12 :         let mut lsn = Lsn(0x10);
    7955           12 :         #[allow(clippy::needless_range_loop)]
    7956        12012 :         for blknum in 0..NUM_KEYS {
    7957        12000 :             lsn = Lsn(lsn.0 + 0x10);
    7958        12000 :             test_key.field6 = (blknum * STEP) as u32;
    7959        12000 :             let mut writer = tline.writer().await;
    7960        12000 :             writer
    7961        12000 :                 .put(
    7962        12000 :                     test_key,
    7963        12000 :                     lsn,
    7964        12000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7965        12000 :                     &ctx,
    7966        12000 :                 )
    7967        12000 :                 .await?;
    7968        12000 :             writer.finish_write(lsn);
    7969        12000 :             updated[blknum] = lsn;
    7970        12000 :             drop(writer);
    7971           12 :         }
    7972           12 : 
    7973           12 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7974           12 : 
    7975          144 :         for iter in 0..=10 {
    7976           12 :             // Read all the blocks
    7977       132000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7978       132000 :                 test_key.field6 = (blknum * STEP) as u32;
    7979       132000 :                 assert_eq!(
    7980       132000 :                     tline.get(test_key, lsn, &ctx).await?,
    7981       132000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7982           12 :                 );
    7983           12 :             }
    7984           12 : 
    7985          132 :             let mut cnt = 0;
    7986          132 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    7987           12 : 
    7988       132000 :             for (key, value) in tline
    7989          132 :                 .get_vectored_impl(
    7990          132 :                     query,
    7991          132 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7992          132 :                     &ctx,
    7993          132 :                 )
    7994          132 :                 .await?
    7995           12 :             {
    7996       132000 :                 let blknum = key.field6 as usize;
    7997       132000 :                 let value = value?;
    7998       132000 :                 assert!(blknum % STEP == 0);
    7999       132000 :                 let blknum = blknum / STEP;
    8000       132000 :                 assert_eq!(
    8001       132000 :                     value,
    8002       132000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8003       132000 :                 );
    8004       132000 :                 cnt += 1;
    8005           12 :             }
    8006           12 : 
    8007          132 :             assert_eq!(cnt, NUM_KEYS);
    8008           12 : 
    8009       132132 :             for _ in 0..NUM_KEYS {
    8010       132000 :                 lsn = Lsn(lsn.0 + 0x10);
    8011       132000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8012       132000 :                 test_key.field6 = (blknum * STEP) as u32;
    8013       132000 :                 let mut writer = tline.writer().await;
    8014       132000 :                 writer
    8015       132000 :                     .put(
    8016       132000 :                         test_key,
    8017       132000 :                         lsn,
    8018       132000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8019       132000 :                         &ctx,
    8020       132000 :                     )
    8021       132000 :                     .await?;
    8022       132000 :                 writer.finish_write(lsn);
    8023       132000 :                 drop(writer);
    8024       132000 :                 updated[blknum] = lsn;
    8025           12 :             }
    8026           12 : 
    8027           12 :             // Perform two cycles of flush, compact, and GC
    8028          396 :             for round in 0..2 {
    8029          264 :                 tline.freeze_and_flush().await?;
    8030          264 :                 tline
    8031          264 :                     .compact(
    8032          264 :                         &cancel,
    8033          264 :                         if iter % 5 == 0 && round == 0 {
    8034           36 :                             let mut flags = EnumSet::new();
    8035           36 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8036           36 :                             flags.insert(CompactFlags::ForceRepartition);
    8037           36 :                             flags
    8038           12 :                         } else {
    8039          228 :                             EnumSet::empty()
    8040           12 :                         },
    8041          264 :                         &ctx,
    8042          264 :                     )
    8043          264 :                     .await?;
    8044          264 :                 tenant
    8045          264 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8046          264 :                     .await?;
    8047           12 :             }
    8048           12 :         }
    8049           12 : 
    8050           12 :         Ok(())
    8051           12 :     }
    8052              : 
    8053              :     #[tokio::test]
    8054           12 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8055           12 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8056           12 :         let (tenant, ctx) = harness.load().await;
    8057           12 :         let tline = tenant
    8058           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8059           12 :             .await?;
    8060           12 : 
    8061           12 :         let cancel = CancellationToken::new();
    8062           12 : 
    8063           12 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8064           12 :         base_key.field1 = AUX_KEY_PREFIX;
    8065           12 :         let test_key = base_key;
    8066           12 :         let mut lsn = Lsn(0x10);
    8067           12 : 
    8068          252 :         for _ in 0..20 {
    8069          240 :             lsn = Lsn(lsn.0 + 0x10);
    8070          240 :             let mut writer = tline.writer().await;
    8071          240 :             writer
    8072          240 :                 .put(
    8073          240 :                     test_key,
    8074          240 :                     lsn,
    8075          240 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8076          240 :                     &ctx,
    8077          240 :                 )
    8078          240 :                 .await?;
    8079          240 :             writer.finish_write(lsn);
    8080          240 :             drop(writer);
    8081          240 :             tline.freeze_and_flush().await?; // force create a delta layer
    8082           12 :         }
    8083           12 : 
    8084           12 :         let before_num_l0_delta_files =
    8085           12 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    8086           12 : 
    8087           12 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8088           12 : 
    8089           12 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    8090           12 : 
    8091           12 :         assert!(
    8092           12 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8093           12 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8094           12 :         );
    8095           12 : 
    8096           12 :         assert_eq!(
    8097           12 :             tline.get(test_key, lsn, &ctx).await?,
    8098           12 :             test_img(&format!("{} at {}", 0, lsn))
    8099           12 :         );
    8100           12 : 
    8101           12 :         Ok(())
    8102           12 :     }
    8103              : 
    8104              :     #[tokio::test]
    8105           12 :     async fn test_aux_file_e2e() {
    8106           12 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8107           12 : 
    8108           12 :         let (tenant, ctx) = harness.load().await;
    8109           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8110           12 : 
    8111           12 :         let mut lsn = Lsn(0x08);
    8112           12 : 
    8113           12 :         let tline: Arc<Timeline> = tenant
    8114           12 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8115           12 :             .await
    8116           12 :             .unwrap();
    8117           12 : 
    8118           12 :         {
    8119           12 :             lsn += 8;
    8120           12 :             let mut modification = tline.begin_modification(lsn);
    8121           12 :             modification
    8122           12 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8123           12 :                 .await
    8124           12 :                 .unwrap();
    8125           12 :             modification.commit(&ctx).await.unwrap();
    8126           12 :         }
    8127           12 : 
    8128           12 :         // we can read everything from the storage
    8129           12 :         let files = tline
    8130           12 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8131           12 :             .await
    8132           12 :             .unwrap();
    8133           12 :         assert_eq!(
    8134           12 :             files.get("pg_logical/mappings/test1"),
    8135           12 :             Some(&bytes::Bytes::from_static(b"first"))
    8136           12 :         );
    8137           12 : 
    8138           12 :         {
    8139           12 :             lsn += 8;
    8140           12 :             let mut modification = tline.begin_modification(lsn);
    8141           12 :             modification
    8142           12 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8143           12 :                 .await
    8144           12 :                 .unwrap();
    8145           12 :             modification.commit(&ctx).await.unwrap();
    8146           12 :         }
    8147           12 : 
    8148           12 :         let files = tline
    8149           12 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8150           12 :             .await
    8151           12 :             .unwrap();
    8152           12 :         assert_eq!(
    8153           12 :             files.get("pg_logical/mappings/test2"),
    8154           12 :             Some(&bytes::Bytes::from_static(b"second"))
    8155           12 :         );
    8156           12 : 
    8157           12 :         let child = tenant
    8158           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8159           12 :             .await
    8160           12 :             .unwrap();
    8161           12 : 
    8162           12 :         let files = child
    8163           12 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8164           12 :             .await
    8165           12 :             .unwrap();
    8166           12 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8167           12 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8168           12 :     }
    8169              : 
    8170              :     #[tokio::test]
    8171           12 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8172           12 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8173           12 :         let (tenant, ctx) = harness.load().await;
    8174           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8175           12 :         let tline = tenant
    8176           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8177           12 :             .await?;
    8178           12 : 
    8179           12 :         const NUM_KEYS: usize = 1000;
    8180           12 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8181           12 : 
    8182           12 :         let cancel = CancellationToken::new();
    8183           12 : 
    8184           12 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8185           12 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8186           12 :         let mut test_key = base_key;
    8187           12 :         let mut lsn = Lsn(0x10);
    8188           12 : 
    8189           48 :         async fn scan_with_statistics(
    8190           48 :             tline: &Timeline,
    8191           48 :             keyspace: &KeySpace,
    8192           48 :             lsn: Lsn,
    8193           48 :             ctx: &RequestContext,
    8194           48 :             io_concurrency: IoConcurrency,
    8195           48 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8196           48 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8197           48 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8198           48 :             let res = tline
    8199           48 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8200           48 :                 .await?;
    8201           48 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8202           48 :         }
    8203           12 : 
    8204        12012 :         for blknum in 0..NUM_KEYS {
    8205        12000 :             lsn = Lsn(lsn.0 + 0x10);
    8206        12000 :             test_key.field6 = (blknum * STEP) as u32;
    8207        12000 :             let mut writer = tline.writer().await;
    8208        12000 :             writer
    8209        12000 :                 .put(
    8210        12000 :                     test_key,
    8211        12000 :                     lsn,
    8212        12000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8213        12000 :                     &ctx,
    8214        12000 :                 )
    8215        12000 :                 .await?;
    8216        12000 :             writer.finish_write(lsn);
    8217        12000 :             drop(writer);
    8218           12 :         }
    8219           12 : 
    8220           12 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8221           12 : 
    8222          132 :         for iter in 1..=10 {
    8223       120120 :             for _ in 0..NUM_KEYS {
    8224       120000 :                 lsn = Lsn(lsn.0 + 0x10);
    8225       120000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8226       120000 :                 test_key.field6 = (blknum * STEP) as u32;
    8227       120000 :                 let mut writer = tline.writer().await;
    8228       120000 :                 writer
    8229       120000 :                     .put(
    8230       120000 :                         test_key,
    8231       120000 :                         lsn,
    8232       120000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8233       120000 :                         &ctx,
    8234       120000 :                     )
    8235       120000 :                     .await?;
    8236       120000 :                 writer.finish_write(lsn);
    8237       120000 :                 drop(writer);
    8238           12 :             }
    8239           12 : 
    8240          120 :             tline.freeze_and_flush().await?;
    8241           12 : 
    8242          120 :             if iter % 5 == 0 {
    8243           24 :                 let (_, before_delta_file_accessed) =
    8244           24 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    8245           24 :                         .await?;
    8246           24 :                 tline
    8247           24 :                     .compact(
    8248           24 :                         &cancel,
    8249           24 :                         {
    8250           24 :                             let mut flags = EnumSet::new();
    8251           24 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8252           24 :                             flags.insert(CompactFlags::ForceRepartition);
    8253           24 :                             flags
    8254           24 :                         },
    8255           24 :                         &ctx,
    8256           24 :                     )
    8257           24 :                     .await?;
    8258           24 :                 let (_, after_delta_file_accessed) =
    8259           24 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    8260           24 :                         .await?;
    8261           24 :                 assert!(
    8262           24 :                     after_delta_file_accessed < before_delta_file_accessed,
    8263           12 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8264           12 :                 );
    8265           12 :                 // 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           24 :                 assert!(
    8267           24 :                     after_delta_file_accessed <= 2,
    8268           12 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8269           12 :                 );
    8270           96 :             }
    8271           12 :         }
    8272           12 : 
    8273           12 :         Ok(())
    8274           12 :     }
    8275              : 
    8276              :     #[tokio::test]
    8277           12 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8278           12 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8279           12 :         let (tenant, ctx) = harness.load().await;
    8280           12 : 
    8281           12 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8282           12 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8283           12 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8284           12 : 
    8285           12 :         let tline = tenant
    8286           12 :             .create_test_timeline_with_layers(
    8287           12 :                 TIMELINE_ID,
    8288           12 :                 Lsn(0x10),
    8289           12 :                 DEFAULT_PG_VERSION,
    8290           12 :                 &ctx,
    8291           12 :                 Vec::new(), // in-memory layers
    8292           12 :                 Vec::new(), // delta layers
    8293           12 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8294           12 :                 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           12 :             )
    8296           12 :             .await?;
    8297           12 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8298           12 : 
    8299           12 :         let child = tenant
    8300           12 :             .branch_timeline_test_with_layers(
    8301           12 :                 &tline,
    8302           12 :                 NEW_TIMELINE_ID,
    8303           12 :                 Some(Lsn(0x20)),
    8304           12 :                 &ctx,
    8305           12 :                 Vec::new(), // delta layers
    8306           12 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8307           12 :                 Lsn(0x30),
    8308           12 :             )
    8309           12 :             .await
    8310           12 :             .unwrap();
    8311           12 : 
    8312           12 :         let lsn = Lsn(0x30);
    8313           12 : 
    8314           12 :         // test vectored get on parent timeline
    8315           12 :         assert_eq!(
    8316           12 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8317           12 :             Some(test_img("data key 1"))
    8318           12 :         );
    8319           12 :         assert!(
    8320           12 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8321           12 :                 .await
    8322           12 :                 .unwrap_err()
    8323           12 :                 .is_missing_key_error()
    8324           12 :         );
    8325           12 :         assert!(
    8326           12 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8327           12 :                 .await
    8328           12 :                 .unwrap_err()
    8329           12 :                 .is_missing_key_error()
    8330           12 :         );
    8331           12 : 
    8332           12 :         // test vectored get on child timeline
    8333           12 :         assert_eq!(
    8334           12 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8335           12 :             Some(test_img("data key 1"))
    8336           12 :         );
    8337           12 :         assert_eq!(
    8338           12 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8339           12 :             Some(test_img("data key 2"))
    8340           12 :         );
    8341           12 :         assert!(
    8342           12 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8343           12 :                 .await
    8344           12 :                 .unwrap_err()
    8345           12 :                 .is_missing_key_error()
    8346           12 :         );
    8347           12 : 
    8348           12 :         Ok(())
    8349           12 :     }
    8350              : 
    8351              :     #[tokio::test]
    8352           12 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8353           12 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8354           12 :         let (tenant, ctx) = harness.load().await;
    8355           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8356           12 : 
    8357           12 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8358           12 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8359           12 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8360           12 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8361           12 : 
    8362           12 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8363           12 :         let base_inherited_key_child =
    8364           12 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8365           12 :         let base_inherited_key_nonexist =
    8366           12 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8367           12 :         let base_inherited_key_overwrite =
    8368           12 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8369           12 : 
    8370           12 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8371           12 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8372           12 : 
    8373           12 :         let tline = tenant
    8374           12 :             .create_test_timeline_with_layers(
    8375           12 :                 TIMELINE_ID,
    8376           12 :                 Lsn(0x10),
    8377           12 :                 DEFAULT_PG_VERSION,
    8378           12 :                 &ctx,
    8379           12 :                 Vec::new(), // in-memory layers
    8380           12 :                 Vec::new(), // delta layers
    8381           12 :                 vec![(
    8382           12 :                     Lsn(0x20),
    8383           12 :                     vec![
    8384           12 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8385           12 :                         (
    8386           12 :                             base_inherited_key_overwrite,
    8387           12 :                             test_img("metadata key overwrite 1a"),
    8388           12 :                         ),
    8389           12 :                         (base_key, test_img("metadata key 1")),
    8390           12 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8391           12 :                     ],
    8392           12 :                 )], // image layers
    8393           12 :                 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           12 :             )
    8395           12 :             .await?;
    8396           12 : 
    8397           12 :         let child = tenant
    8398           12 :             .branch_timeline_test_with_layers(
    8399           12 :                 &tline,
    8400           12 :                 NEW_TIMELINE_ID,
    8401           12 :                 Some(Lsn(0x20)),
    8402           12 :                 &ctx,
    8403           12 :                 Vec::new(), // delta layers
    8404           12 :                 vec![(
    8405           12 :                     Lsn(0x30),
    8406           12 :                     vec![
    8407           12 :                         (
    8408           12 :                             base_inherited_key_child,
    8409           12 :                             test_img("metadata inherited key 2"),
    8410           12 :                         ),
    8411           12 :                         (
    8412           12 :                             base_inherited_key_overwrite,
    8413           12 :                             test_img("metadata key overwrite 2a"),
    8414           12 :                         ),
    8415           12 :                         (base_key_child, test_img("metadata key 2")),
    8416           12 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8417           12 :                     ],
    8418           12 :                 )], // image layers
    8419           12 :                 Lsn(0x30),
    8420           12 :             )
    8421           12 :             .await
    8422           12 :             .unwrap();
    8423           12 : 
    8424           12 :         let lsn = Lsn(0x30);
    8425           12 : 
    8426           12 :         // test vectored get on parent timeline
    8427           12 :         assert_eq!(
    8428           12 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8429           12 :             Some(test_img("metadata key 1"))
    8430           12 :         );
    8431           12 :         assert_eq!(
    8432           12 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8433           12 :             None
    8434           12 :         );
    8435           12 :         assert_eq!(
    8436           12 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8437           12 :             None
    8438           12 :         );
    8439           12 :         assert_eq!(
    8440           12 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8441           12 :             Some(test_img("metadata key overwrite 1b"))
    8442           12 :         );
    8443           12 :         assert_eq!(
    8444           12 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8445           12 :             Some(test_img("metadata inherited key 1"))
    8446           12 :         );
    8447           12 :         assert_eq!(
    8448           12 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8449           12 :             None
    8450           12 :         );
    8451           12 :         assert_eq!(
    8452           12 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8453           12 :             None
    8454           12 :         );
    8455           12 :         assert_eq!(
    8456           12 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8457           12 :             Some(test_img("metadata key overwrite 1a"))
    8458           12 :         );
    8459           12 : 
    8460           12 :         // test vectored get on child timeline
    8461           12 :         assert_eq!(
    8462           12 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8463           12 :             None
    8464           12 :         );
    8465           12 :         assert_eq!(
    8466           12 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8467           12 :             Some(test_img("metadata key 2"))
    8468           12 :         );
    8469           12 :         assert_eq!(
    8470           12 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8471           12 :             None
    8472           12 :         );
    8473           12 :         assert_eq!(
    8474           12 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8475           12 :             Some(test_img("metadata inherited key 1"))
    8476           12 :         );
    8477           12 :         assert_eq!(
    8478           12 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8479           12 :             Some(test_img("metadata inherited key 2"))
    8480           12 :         );
    8481           12 :         assert_eq!(
    8482           12 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8483           12 :             None
    8484           12 :         );
    8485           12 :         assert_eq!(
    8486           12 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8487           12 :             Some(test_img("metadata key overwrite 2b"))
    8488           12 :         );
    8489           12 :         assert_eq!(
    8490           12 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8491           12 :             Some(test_img("metadata key overwrite 2a"))
    8492           12 :         );
    8493           12 : 
    8494           12 :         // test vectored scan on parent timeline
    8495           12 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8496           12 :         let query =
    8497           12 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8498           12 :         let res = tline
    8499           12 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8500           12 :             .await?;
    8501           12 : 
    8502           12 :         assert_eq!(
    8503           12 :             res.into_iter()
    8504           48 :                 .map(|(k, v)| (k, v.unwrap()))
    8505           12 :                 .collect::<Vec<_>>(),
    8506           12 :             vec![
    8507           12 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8508           12 :                 (
    8509           12 :                     base_inherited_key_overwrite,
    8510           12 :                     test_img("metadata key overwrite 1a")
    8511           12 :                 ),
    8512           12 :                 (base_key, test_img("metadata key 1")),
    8513           12 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8514           12 :             ]
    8515           12 :         );
    8516           12 : 
    8517           12 :         // test vectored scan on child timeline
    8518           12 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8519           12 :         let query =
    8520           12 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8521           12 :         let res = child
    8522           12 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8523           12 :             .await?;
    8524           12 : 
    8525           12 :         assert_eq!(
    8526           12 :             res.into_iter()
    8527           60 :                 .map(|(k, v)| (k, v.unwrap()))
    8528           12 :                 .collect::<Vec<_>>(),
    8529           12 :             vec![
    8530           12 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8531           12 :                 (
    8532           12 :                     base_inherited_key_child,
    8533           12 :                     test_img("metadata inherited key 2")
    8534           12 :                 ),
    8535           12 :                 (
    8536           12 :                     base_inherited_key_overwrite,
    8537           12 :                     test_img("metadata key overwrite 2a")
    8538           12 :                 ),
    8539           12 :                 (base_key_child, test_img("metadata key 2")),
    8540           12 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8541           12 :             ]
    8542           12 :         );
    8543           12 : 
    8544           12 :         Ok(())
    8545           12 :     }
    8546              : 
    8547          336 :     async fn get_vectored_impl_wrapper(
    8548          336 :         tline: &Arc<Timeline>,
    8549          336 :         key: Key,
    8550          336 :         lsn: Lsn,
    8551          336 :         ctx: &RequestContext,
    8552          336 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8553          336 :         let io_concurrency =
    8554          336 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    8555          336 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8556          336 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8557          336 :         let mut res = tline
    8558          336 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8559          336 :             .await?;
    8560          300 :         Ok(res.pop_last().map(|(k, v)| {
    8561          192 :             assert_eq!(k, key);
    8562          192 :             v.unwrap()
    8563          300 :         }))
    8564          336 :     }
    8565              : 
    8566              :     #[tokio::test]
    8567           12 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8568           12 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8569           12 :         let (tenant, ctx) = harness.load().await;
    8570           12 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8571           12 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8572           12 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8573           12 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8574           12 : 
    8575           12 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8576           12 :         // Lsn 0x30 key0, key3, no key1+key2
    8577           12 :         // Lsn 0x20 key1+key2 tomestones
    8578           12 :         // Lsn 0x10 key1 in image, key2 in delta
    8579           12 :         let tline = tenant
    8580           12 :             .create_test_timeline_with_layers(
    8581           12 :                 TIMELINE_ID,
    8582           12 :                 Lsn(0x10),
    8583           12 :                 DEFAULT_PG_VERSION,
    8584           12 :                 &ctx,
    8585           12 :                 Vec::new(), // in-memory layers
    8586           12 :                 // delta layers
    8587           12 :                 vec![
    8588           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8589           12 :                         Lsn(0x10)..Lsn(0x20),
    8590           12 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8591           12 :                     ),
    8592           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8593           12 :                         Lsn(0x20)..Lsn(0x30),
    8594           12 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8595           12 :                     ),
    8596           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8597           12 :                         Lsn(0x20)..Lsn(0x30),
    8598           12 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8599           12 :                     ),
    8600           12 :                 ],
    8601           12 :                 // image layers
    8602           12 :                 vec![
    8603           12 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8604           12 :                     (
    8605           12 :                         Lsn(0x30),
    8606           12 :                         vec![
    8607           12 :                             (key0, test_img("metadata key 0")),
    8608           12 :                             (key3, test_img("metadata key 3")),
    8609           12 :                         ],
    8610           12 :                     ),
    8611           12 :                 ],
    8612           12 :                 Lsn(0x30),
    8613           12 :             )
    8614           12 :             .await?;
    8615           12 : 
    8616           12 :         let lsn = Lsn(0x30);
    8617           12 :         let old_lsn = Lsn(0x20);
    8618           12 : 
    8619           12 :         assert_eq!(
    8620           12 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8621           12 :             Some(test_img("metadata key 0"))
    8622           12 :         );
    8623           12 :         assert_eq!(
    8624           12 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8625           12 :             None,
    8626           12 :         );
    8627           12 :         assert_eq!(
    8628           12 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8629           12 :             None,
    8630           12 :         );
    8631           12 :         assert_eq!(
    8632           12 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8633           12 :             Some(Bytes::new()),
    8634           12 :         );
    8635           12 :         assert_eq!(
    8636           12 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8637           12 :             Some(Bytes::new()),
    8638           12 :         );
    8639           12 :         assert_eq!(
    8640           12 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8641           12 :             Some(test_img("metadata key 3"))
    8642           12 :         );
    8643           12 : 
    8644           12 :         Ok(())
    8645           12 :     }
    8646              : 
    8647              :     #[tokio::test]
    8648           12 :     async fn test_metadata_tombstone_image_creation() {
    8649           12 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8650           12 :             .await
    8651           12 :             .unwrap();
    8652           12 :         let (tenant, ctx) = harness.load().await;
    8653           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8654           12 : 
    8655           12 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8656           12 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8657           12 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8658           12 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8659           12 : 
    8660           12 :         let tline = tenant
    8661           12 :             .create_test_timeline_with_layers(
    8662           12 :                 TIMELINE_ID,
    8663           12 :                 Lsn(0x10),
    8664           12 :                 DEFAULT_PG_VERSION,
    8665           12 :                 &ctx,
    8666           12 :                 Vec::new(), // in-memory layers
    8667           12 :                 // delta layers
    8668           12 :                 vec![
    8669           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8670           12 :                         Lsn(0x10)..Lsn(0x20),
    8671           12 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8672           12 :                     ),
    8673           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8674           12 :                         Lsn(0x20)..Lsn(0x30),
    8675           12 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8676           12 :                     ),
    8677           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8678           12 :                         Lsn(0x20)..Lsn(0x30),
    8679           12 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8680           12 :                     ),
    8681           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8682           12 :                         Lsn(0x30)..Lsn(0x40),
    8683           12 :                         vec![
    8684           12 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8685           12 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8686           12 :                         ],
    8687           12 :                     ),
    8688           12 :                 ],
    8689           12 :                 // image layers
    8690           12 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8691           12 :                 Lsn(0x40),
    8692           12 :             )
    8693           12 :             .await
    8694           12 :             .unwrap();
    8695           12 : 
    8696           12 :         let cancel = CancellationToken::new();
    8697           12 : 
    8698           12 :         tline
    8699           12 :             .compact(
    8700           12 :                 &cancel,
    8701           12 :                 {
    8702           12 :                     let mut flags = EnumSet::new();
    8703           12 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8704           12 :                     flags.insert(CompactFlags::ForceRepartition);
    8705           12 :                     flags
    8706           12 :                 },
    8707           12 :                 &ctx,
    8708           12 :             )
    8709           12 :             .await
    8710           12 :             .unwrap();
    8711           12 : 
    8712           12 :         // Image layers are created at last_record_lsn
    8713           12 :         let images = tline
    8714           12 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8715           12 :             .await
    8716           12 :             .unwrap()
    8717           12 :             .into_iter()
    8718          108 :             .filter(|(k, _)| k.is_metadata_key())
    8719           12 :             .collect::<Vec<_>>();
    8720           12 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8721           12 :     }
    8722              : 
    8723              :     #[tokio::test]
    8724           12 :     async fn test_metadata_tombstone_empty_image_creation() {
    8725           12 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8726           12 :             .await
    8727           12 :             .unwrap();
    8728           12 :         let (tenant, ctx) = harness.load().await;
    8729           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8730           12 : 
    8731           12 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8732           12 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8733           12 : 
    8734           12 :         let tline = tenant
    8735           12 :             .create_test_timeline_with_layers(
    8736           12 :                 TIMELINE_ID,
    8737           12 :                 Lsn(0x10),
    8738           12 :                 DEFAULT_PG_VERSION,
    8739           12 :                 &ctx,
    8740           12 :                 Vec::new(), // in-memory layers
    8741           12 :                 // delta layers
    8742           12 :                 vec![
    8743           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8744           12 :                         Lsn(0x10)..Lsn(0x20),
    8745           12 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8746           12 :                     ),
    8747           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8748           12 :                         Lsn(0x20)..Lsn(0x30),
    8749           12 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8750           12 :                     ),
    8751           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8752           12 :                         Lsn(0x20)..Lsn(0x30),
    8753           12 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8754           12 :                     ),
    8755           12 :                 ],
    8756           12 :                 // image layers
    8757           12 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8758           12 :                 Lsn(0x30),
    8759           12 :             )
    8760           12 :             .await
    8761           12 :             .unwrap();
    8762           12 : 
    8763           12 :         let cancel = CancellationToken::new();
    8764           12 : 
    8765           12 :         tline
    8766           12 :             .compact(
    8767           12 :                 &cancel,
    8768           12 :                 {
    8769           12 :                     let mut flags = EnumSet::new();
    8770           12 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8771           12 :                     flags.insert(CompactFlags::ForceRepartition);
    8772           12 :                     flags
    8773           12 :                 },
    8774           12 :                 &ctx,
    8775           12 :             )
    8776           12 :             .await
    8777           12 :             .unwrap();
    8778           12 : 
    8779           12 :         // Image layers are created at last_record_lsn
    8780           12 :         let images = tline
    8781           12 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8782           12 :             .await
    8783           12 :             .unwrap()
    8784           12 :             .into_iter()
    8785           84 :             .filter(|(k, _)| k.is_metadata_key())
    8786           12 :             .collect::<Vec<_>>();
    8787           12 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8788           12 :     }
    8789              : 
    8790              :     #[tokio::test]
    8791           12 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8792           12 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8793           12 :         let (tenant, ctx) = harness.load().await;
    8794           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8795           12 : 
    8796          612 :         fn get_key(id: u32) -> Key {
    8797          612 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8798          612 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8799          612 :             key.field6 = id;
    8800          612 :             key
    8801          612 :         }
    8802           12 : 
    8803           12 :         // We create
    8804           12 :         // - one bottom-most image layer,
    8805           12 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8806           12 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8807           12 :         // - a delta layer D3 above the horizon.
    8808           12 :         //
    8809           12 :         //                             | D3 |
    8810           12 :         //  | D1 |
    8811           12 :         // -|    |-- gc horizon -----------------
    8812           12 :         //  |    |                | D2 |
    8813           12 :         // --------- img layer ------------------
    8814           12 :         //
    8815           12 :         // What we should expact from this compaction is:
    8816           12 :         //                             | D3 |
    8817           12 :         //  | Part of D1 |
    8818           12 :         // --------- img layer with D1+D2 at GC horizon------------------
    8819           12 : 
    8820           12 :         // img layer at 0x10
    8821           12 :         let img_layer = (0..10)
    8822          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8823           12 :             .collect_vec();
    8824           12 : 
    8825           12 :         let delta1 = vec![
    8826           12 :             (
    8827           12 :                 get_key(1),
    8828           12 :                 Lsn(0x20),
    8829           12 :                 Value::Image(Bytes::from("value 1@0x20")),
    8830           12 :             ),
    8831           12 :             (
    8832           12 :                 get_key(2),
    8833           12 :                 Lsn(0x30),
    8834           12 :                 Value::Image(Bytes::from("value 2@0x30")),
    8835           12 :             ),
    8836           12 :             (
    8837           12 :                 get_key(3),
    8838           12 :                 Lsn(0x40),
    8839           12 :                 Value::Image(Bytes::from("value 3@0x40")),
    8840           12 :             ),
    8841           12 :         ];
    8842           12 :         let delta2 = vec![
    8843           12 :             (
    8844           12 :                 get_key(5),
    8845           12 :                 Lsn(0x20),
    8846           12 :                 Value::Image(Bytes::from("value 5@0x20")),
    8847           12 :             ),
    8848           12 :             (
    8849           12 :                 get_key(6),
    8850           12 :                 Lsn(0x20),
    8851           12 :                 Value::Image(Bytes::from("value 6@0x20")),
    8852           12 :             ),
    8853           12 :         ];
    8854           12 :         let delta3 = vec![
    8855           12 :             (
    8856           12 :                 get_key(8),
    8857           12 :                 Lsn(0x48),
    8858           12 :                 Value::Image(Bytes::from("value 8@0x48")),
    8859           12 :             ),
    8860           12 :             (
    8861           12 :                 get_key(9),
    8862           12 :                 Lsn(0x48),
    8863           12 :                 Value::Image(Bytes::from("value 9@0x48")),
    8864           12 :             ),
    8865           12 :         ];
    8866           12 : 
    8867           12 :         let tline = tenant
    8868           12 :             .create_test_timeline_with_layers(
    8869           12 :                 TIMELINE_ID,
    8870           12 :                 Lsn(0x10),
    8871           12 :                 DEFAULT_PG_VERSION,
    8872           12 :                 &ctx,
    8873           12 :                 Vec::new(), // in-memory layers
    8874           12 :                 vec![
    8875           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8876           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8877           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8878           12 :                 ], // delta layers
    8879           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8880           12 :                 Lsn(0x50),
    8881           12 :             )
    8882           12 :             .await?;
    8883           12 :         {
    8884           12 :             tline
    8885           12 :                 .applied_gc_cutoff_lsn
    8886           12 :                 .lock_for_write()
    8887           12 :                 .store_and_unlock(Lsn(0x30))
    8888           12 :                 .wait()
    8889           12 :                 .await;
    8890           12 :             // Update GC info
    8891           12 :             let mut guard = tline.gc_info.write().unwrap();
    8892           12 :             guard.cutoffs.time = Lsn(0x30);
    8893           12 :             guard.cutoffs.space = Lsn(0x30);
    8894           12 :         }
    8895           12 : 
    8896           12 :         let expected_result = [
    8897           12 :             Bytes::from_static(b"value 0@0x10"),
    8898           12 :             Bytes::from_static(b"value 1@0x20"),
    8899           12 :             Bytes::from_static(b"value 2@0x30"),
    8900           12 :             Bytes::from_static(b"value 3@0x40"),
    8901           12 :             Bytes::from_static(b"value 4@0x10"),
    8902           12 :             Bytes::from_static(b"value 5@0x20"),
    8903           12 :             Bytes::from_static(b"value 6@0x20"),
    8904           12 :             Bytes::from_static(b"value 7@0x10"),
    8905           12 :             Bytes::from_static(b"value 8@0x48"),
    8906           12 :             Bytes::from_static(b"value 9@0x48"),
    8907           12 :         ];
    8908           12 : 
    8909          120 :         for (idx, expected) in expected_result.iter().enumerate() {
    8910          120 :             assert_eq!(
    8911          120 :                 tline
    8912          120 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8913          120 :                     .await
    8914          120 :                     .unwrap(),
    8915           12 :                 expected
    8916           12 :             );
    8917           12 :         }
    8918           12 : 
    8919           12 :         let cancel = CancellationToken::new();
    8920           12 :         tline
    8921           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8922           12 :             .await
    8923           12 :             .unwrap();
    8924           12 : 
    8925          120 :         for (idx, expected) in expected_result.iter().enumerate() {
    8926          120 :             assert_eq!(
    8927          120 :                 tline
    8928          120 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8929          120 :                     .await
    8930          120 :                     .unwrap(),
    8931           12 :                 expected
    8932           12 :             );
    8933           12 :         }
    8934           12 : 
    8935           12 :         // Check if the image layer at the GC horizon contains exactly what we want
    8936           12 :         let image_at_gc_horizon = tline
    8937           12 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8938           12 :             .await
    8939           12 :             .unwrap()
    8940           12 :             .into_iter()
    8941          204 :             .filter(|(k, _)| k.is_metadata_key())
    8942           12 :             .collect::<Vec<_>>();
    8943           12 : 
    8944           12 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8945           12 :         let expected_result = [
    8946           12 :             Bytes::from_static(b"value 0@0x10"),
    8947           12 :             Bytes::from_static(b"value 1@0x20"),
    8948           12 :             Bytes::from_static(b"value 2@0x30"),
    8949           12 :             Bytes::from_static(b"value 3@0x10"),
    8950           12 :             Bytes::from_static(b"value 4@0x10"),
    8951           12 :             Bytes::from_static(b"value 5@0x20"),
    8952           12 :             Bytes::from_static(b"value 6@0x20"),
    8953           12 :             Bytes::from_static(b"value 7@0x10"),
    8954           12 :             Bytes::from_static(b"value 8@0x10"),
    8955           12 :             Bytes::from_static(b"value 9@0x10"),
    8956           12 :         ];
    8957          132 :         for idx in 0..10 {
    8958          120 :             assert_eq!(
    8959          120 :                 image_at_gc_horizon[idx],
    8960          120 :                 (get_key(idx as u32), expected_result[idx].clone())
    8961          120 :             );
    8962           12 :         }
    8963           12 : 
    8964           12 :         // Check if old layers are removed / new layers have the expected LSN
    8965           12 :         let all_layers = inspect_and_sort(&tline, None).await;
    8966           12 :         assert_eq!(
    8967           12 :             all_layers,
    8968           12 :             vec![
    8969           12 :                 // Image layer at GC horizon
    8970           12 :                 PersistentLayerKey {
    8971           12 :                     key_range: Key::MIN..Key::MAX,
    8972           12 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8973           12 :                     is_delta: false
    8974           12 :                 },
    8975           12 :                 // The delta layer below the horizon
    8976           12 :                 PersistentLayerKey {
    8977           12 :                     key_range: get_key(3)..get_key(4),
    8978           12 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8979           12 :                     is_delta: true
    8980           12 :                 },
    8981           12 :                 // The delta3 layer that should not be picked for the compaction
    8982           12 :                 PersistentLayerKey {
    8983           12 :                     key_range: get_key(8)..get_key(10),
    8984           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8985           12 :                     is_delta: true
    8986           12 :                 }
    8987           12 :             ]
    8988           12 :         );
    8989           12 : 
    8990           12 :         // increase GC horizon and compact again
    8991           12 :         {
    8992           12 :             tline
    8993           12 :                 .applied_gc_cutoff_lsn
    8994           12 :                 .lock_for_write()
    8995           12 :                 .store_and_unlock(Lsn(0x40))
    8996           12 :                 .wait()
    8997           12 :                 .await;
    8998           12 :             // Update GC info
    8999           12 :             let mut guard = tline.gc_info.write().unwrap();
    9000           12 :             guard.cutoffs.time = Lsn(0x40);
    9001           12 :             guard.cutoffs.space = Lsn(0x40);
    9002           12 :         }
    9003           12 :         tline
    9004           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9005           12 :             .await
    9006           12 :             .unwrap();
    9007           12 : 
    9008           12 :         Ok(())
    9009           12 :     }
    9010              : 
    9011              :     #[cfg(feature = "testing")]
    9012              :     #[tokio::test]
    9013           12 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9014           12 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9015           12 :         let (tenant, ctx) = harness.load().await;
    9016           12 : 
    9017          204 :         fn get_key(id: u32) -> Key {
    9018          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9019          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9020          204 :             key.field6 = id;
    9021          204 :             key
    9022          204 :         }
    9023           12 : 
    9024           12 :         let delta1 = vec![
    9025           12 :             (
    9026           12 :                 get_key(1),
    9027           12 :                 Lsn(0x20),
    9028           12 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9029           12 :             ),
    9030           12 :             (
    9031           12 :                 get_key(1),
    9032           12 :                 Lsn(0x30),
    9033           12 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9034           12 :             ),
    9035           12 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9036           12 :             (
    9037           12 :                 get_key(2),
    9038           12 :                 Lsn(0x20),
    9039           12 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9040           12 :             ),
    9041           12 :             (
    9042           12 :                 get_key(2),
    9043           12 :                 Lsn(0x30),
    9044           12 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9045           12 :             ),
    9046           12 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9047           12 :             (
    9048           12 :                 get_key(3),
    9049           12 :                 Lsn(0x20),
    9050           12 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9051           12 :             ),
    9052           12 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9053           12 :             (
    9054           12 :                 get_key(4),
    9055           12 :                 Lsn(0x20),
    9056           12 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9057           12 :             ),
    9058           12 :             (
    9059           12 :                 get_key(4),
    9060           12 :                 Lsn(0x30),
    9061           12 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9062           12 :             ),
    9063           12 :             (
    9064           12 :                 get_key(5),
    9065           12 :                 Lsn(0x20),
    9066           12 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9067           12 :             ),
    9068           12 :             (
    9069           12 :                 get_key(5),
    9070           12 :                 Lsn(0x30),
    9071           12 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9072           12 :             ),
    9073           12 :         ];
    9074           12 :         let image1 = vec![(get_key(1), "0x10".into())];
    9075           12 : 
    9076           12 :         let tline = tenant
    9077           12 :             .create_test_timeline_with_layers(
    9078           12 :                 TIMELINE_ID,
    9079           12 :                 Lsn(0x10),
    9080           12 :                 DEFAULT_PG_VERSION,
    9081           12 :                 &ctx,
    9082           12 :                 Vec::new(), // in-memory layers
    9083           12 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9084           12 :                     Lsn(0x10)..Lsn(0x40),
    9085           12 :                     delta1,
    9086           12 :                 )], // delta layers
    9087           12 :                 vec![(Lsn(0x10), image1)], // image layers
    9088           12 :                 Lsn(0x50),
    9089           12 :             )
    9090           12 :             .await?;
    9091           12 : 
    9092           12 :         assert_eq!(
    9093           12 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9094           12 :             Bytes::from_static(b"0x10,0x20,0x30")
    9095           12 :         );
    9096           12 :         assert_eq!(
    9097           12 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9098           12 :             Bytes::from_static(b"0x10,0x20,0x30")
    9099           12 :         );
    9100           12 : 
    9101           12 :         // Need to remove the limit of "Neon WAL redo requires base image".
    9102           12 : 
    9103           12 :         assert_eq!(
    9104           12 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9105           12 :             Bytes::from_static(b"c")
    9106           12 :         );
    9107           12 :         assert_eq!(
    9108           12 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9109           12 :             Bytes::from_static(b"ij")
    9110           12 :         );
    9111           12 : 
    9112           12 :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9113           12 :         // cannot enable this assertion in the unit test.
    9114           12 :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9115           12 : 
    9116           12 :         Ok(())
    9117           12 :     }
    9118              : 
    9119              :     #[tokio::test(start_paused = true)]
    9120           12 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9121           12 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9122           12 :             .await
    9123           12 :             .unwrap()
    9124           12 :             .load()
    9125           12 :             .await;
    9126           12 :         // Advance to the lsn lease deadline so that GC is not blocked by
    9127           12 :         // initial transition into AttachedSingle.
    9128           12 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    9129           12 :         tokio::time::resume();
    9130           12 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9131           12 : 
    9132           12 :         let end_lsn = Lsn(0x100);
    9133           12 :         let image_layers = (0x20..=0x90)
    9134           12 :             .step_by(0x10)
    9135           96 :             .map(|n| {
    9136           96 :                 (
    9137           96 :                     Lsn(n),
    9138           96 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    9139           96 :                 )
    9140           96 :             })
    9141           12 :             .collect();
    9142           12 : 
    9143           12 :         let timeline = tenant
    9144           12 :             .create_test_timeline_with_layers(
    9145           12 :                 TIMELINE_ID,
    9146           12 :                 Lsn(0x10),
    9147           12 :                 DEFAULT_PG_VERSION,
    9148           12 :                 &ctx,
    9149           12 :                 Vec::new(), // in-memory layers
    9150           12 :                 Vec::new(),
    9151           12 :                 image_layers,
    9152           12 :                 end_lsn,
    9153           12 :             )
    9154           12 :             .await?;
    9155           12 : 
    9156           12 :         let leased_lsns = [0x30, 0x50, 0x70];
    9157           12 :         let mut leases = Vec::new();
    9158           36 :         leased_lsns.iter().for_each(|n| {
    9159           36 :             leases.push(
    9160           36 :                 timeline
    9161           36 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9162           36 :                     .expect("lease request should succeed"),
    9163           36 :             );
    9164           36 :         });
    9165           12 : 
    9166           12 :         let updated_lease_0 = timeline
    9167           12 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9168           12 :             .expect("lease renewal should succeed");
    9169           12 :         assert_eq!(
    9170           12 :             updated_lease_0.valid_until, leases[0].valid_until,
    9171           12 :             " Renewing with shorter lease should not change the lease."
    9172           12 :         );
    9173           12 : 
    9174           12 :         let updated_lease_1 = timeline
    9175           12 :             .renew_lsn_lease(
    9176           12 :                 Lsn(leased_lsns[1]),
    9177           12 :                 timeline.get_lsn_lease_length() * 2,
    9178           12 :                 &ctx,
    9179           12 :             )
    9180           12 :             .expect("lease renewal should succeed");
    9181           12 :         assert!(
    9182           12 :             updated_lease_1.valid_until > leases[1].valid_until,
    9183           12 :             "Renewing with a long lease should renew lease with later expiration time."
    9184           12 :         );
    9185           12 : 
    9186           12 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9187           12 :         info!(
    9188           12 :             "applied_gc_cutoff_lsn: {}",
    9189            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9190           12 :         );
    9191           12 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9192           12 : 
    9193           12 :         let res = tenant
    9194           12 :             .gc_iteration(
    9195           12 :                 Some(TIMELINE_ID),
    9196           12 :                 0,
    9197           12 :                 Duration::ZERO,
    9198           12 :                 &CancellationToken::new(),
    9199           12 :                 &ctx,
    9200           12 :             )
    9201           12 :             .await
    9202           12 :             .unwrap();
    9203           12 : 
    9204           12 :         // Keeping everything <= Lsn(0x80) b/c leases:
    9205           12 :         // 0/10: initdb layer
    9206           12 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9207           12 :         assert_eq!(res.layers_needed_by_leases, 7);
    9208           12 :         // Keeping 0/90 b/c it is the latest layer.
    9209           12 :         assert_eq!(res.layers_not_updated, 1);
    9210           12 :         // Removed 0/80.
    9211           12 :         assert_eq!(res.layers_removed, 1);
    9212           12 : 
    9213           12 :         // Make lease on a already GC-ed LSN.
    9214           12 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9215           12 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9216           12 :         timeline
    9217           12 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9218           12 :             .expect_err("lease request on GC-ed LSN should fail");
    9219           12 : 
    9220           12 :         // Should still be able to renew a currently valid lease
    9221           12 :         // Assumption: original lease to is still valid for 0/50.
    9222           12 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9223           12 :         timeline
    9224           12 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9225           12 :             .expect("lease renewal with validation should succeed");
    9226           12 : 
    9227           12 :         Ok(())
    9228           12 :     }
    9229              : 
    9230              :     #[cfg(feature = "testing")]
    9231              :     #[tokio::test]
    9232           12 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9233           12 :         test_simple_bottom_most_compaction_deltas_helper(
    9234           12 :             "test_simple_bottom_most_compaction_deltas_1",
    9235           12 :             false,
    9236           12 :         )
    9237           12 :         .await
    9238           12 :     }
    9239              : 
    9240              :     #[cfg(feature = "testing")]
    9241              :     #[tokio::test]
    9242           12 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9243           12 :         test_simple_bottom_most_compaction_deltas_helper(
    9244           12 :             "test_simple_bottom_most_compaction_deltas_2",
    9245           12 :             true,
    9246           12 :         )
    9247           12 :         .await
    9248           12 :     }
    9249              : 
    9250              :     #[cfg(feature = "testing")]
    9251           24 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9252           24 :         test_name: &'static str,
    9253           24 :         use_delta_bottom_layer: bool,
    9254           24 :     ) -> anyhow::Result<()> {
    9255           24 :         let harness = TenantHarness::create(test_name).await?;
    9256           24 :         let (tenant, ctx) = harness.load().await;
    9257              : 
    9258         1656 :         fn get_key(id: u32) -> Key {
    9259         1656 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9260         1656 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9261         1656 :             key.field6 = id;
    9262         1656 :             key
    9263         1656 :         }
    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           24 :         let img_layer = (0..10)
    9284          240 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9285           24 :             .collect_vec();
    9286           24 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9287           24 :         let delta4 = (0..10)
    9288          240 :             .map(|id| {
    9289          240 :                 (
    9290          240 :                     get_key(id),
    9291          240 :                     Lsn(0x08),
    9292          240 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9293          240 :                 )
    9294          240 :             })
    9295           24 :             .collect_vec();
    9296           24 : 
    9297           24 :         let delta1 = vec![
    9298           24 :             (
    9299           24 :                 get_key(1),
    9300           24 :                 Lsn(0x20),
    9301           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9302           24 :             ),
    9303           24 :             (
    9304           24 :                 get_key(2),
    9305           24 :                 Lsn(0x30),
    9306           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9307           24 :             ),
    9308           24 :             (
    9309           24 :                 get_key(3),
    9310           24 :                 Lsn(0x28),
    9311           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9312           24 :             ),
    9313           24 :             (
    9314           24 :                 get_key(3),
    9315           24 :                 Lsn(0x30),
    9316           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9317           24 :             ),
    9318           24 :             (
    9319           24 :                 get_key(3),
    9320           24 :                 Lsn(0x40),
    9321           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9322           24 :             ),
    9323           24 :         ];
    9324           24 :         let delta2 = vec![
    9325           24 :             (
    9326           24 :                 get_key(5),
    9327           24 :                 Lsn(0x20),
    9328           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9329           24 :             ),
    9330           24 :             (
    9331           24 :                 get_key(6),
    9332           24 :                 Lsn(0x20),
    9333           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9334           24 :             ),
    9335           24 :         ];
    9336           24 :         let delta3 = vec![
    9337           24 :             (
    9338           24 :                 get_key(8),
    9339           24 :                 Lsn(0x48),
    9340           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9341           24 :             ),
    9342           24 :             (
    9343           24 :                 get_key(9),
    9344           24 :                 Lsn(0x48),
    9345           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9346           24 :             ),
    9347           24 :         ];
    9348              : 
    9349           24 :         let tline = if use_delta_bottom_layer {
    9350           12 :             tenant
    9351           12 :                 .create_test_timeline_with_layers(
    9352           12 :                     TIMELINE_ID,
    9353           12 :                     Lsn(0x08),
    9354           12 :                     DEFAULT_PG_VERSION,
    9355           12 :                     &ctx,
    9356           12 :                     Vec::new(), // in-memory layers
    9357           12 :                     vec![
    9358           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9359           12 :                             Lsn(0x08)..Lsn(0x10),
    9360           12 :                             delta4,
    9361           12 :                         ),
    9362           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9363           12 :                             Lsn(0x20)..Lsn(0x48),
    9364           12 :                             delta1,
    9365           12 :                         ),
    9366           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9367           12 :                             Lsn(0x20)..Lsn(0x48),
    9368           12 :                             delta2,
    9369           12 :                         ),
    9370           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9371           12 :                             Lsn(0x48)..Lsn(0x50),
    9372           12 :                             delta3,
    9373           12 :                         ),
    9374           12 :                     ], // delta layers
    9375           12 :                     vec![],     // image layers
    9376           12 :                     Lsn(0x50),
    9377           12 :                 )
    9378           12 :                 .await?
    9379              :         } else {
    9380           12 :             tenant
    9381           12 :                 .create_test_timeline_with_layers(
    9382           12 :                     TIMELINE_ID,
    9383           12 :                     Lsn(0x10),
    9384           12 :                     DEFAULT_PG_VERSION,
    9385           12 :                     &ctx,
    9386           12 :                     Vec::new(), // in-memory layers
    9387           12 :                     vec![
    9388           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9389           12 :                             Lsn(0x10)..Lsn(0x48),
    9390           12 :                             delta1,
    9391           12 :                         ),
    9392           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9393           12 :                             Lsn(0x10)..Lsn(0x48),
    9394           12 :                             delta2,
    9395           12 :                         ),
    9396           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9397           12 :                             Lsn(0x48)..Lsn(0x50),
    9398           12 :                             delta3,
    9399           12 :                         ),
    9400           12 :                     ], // delta layers
    9401           12 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9402           12 :                     Lsn(0x50),
    9403           12 :                 )
    9404           12 :                 .await?
    9405              :         };
    9406              :         {
    9407           24 :             tline
    9408           24 :                 .applied_gc_cutoff_lsn
    9409           24 :                 .lock_for_write()
    9410           24 :                 .store_and_unlock(Lsn(0x30))
    9411           24 :                 .wait()
    9412           24 :                 .await;
    9413              :             // Update GC info
    9414           24 :             let mut guard = tline.gc_info.write().unwrap();
    9415           24 :             *guard = GcInfo {
    9416           24 :                 retain_lsns: vec![],
    9417           24 :                 cutoffs: GcCutoffs {
    9418           24 :                     time: Lsn(0x30),
    9419           24 :                     space: Lsn(0x30),
    9420           24 :                 },
    9421           24 :                 leases: Default::default(),
    9422           24 :                 within_ancestor_pitr: false,
    9423           24 :             };
    9424           24 :         }
    9425           24 : 
    9426           24 :         let expected_result = [
    9427           24 :             Bytes::from_static(b"value 0@0x10"),
    9428           24 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9429           24 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9430           24 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9431           24 :             Bytes::from_static(b"value 4@0x10"),
    9432           24 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9433           24 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9434           24 :             Bytes::from_static(b"value 7@0x10"),
    9435           24 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9436           24 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9437           24 :         ];
    9438           24 : 
    9439           24 :         let expected_result_at_gc_horizon = [
    9440           24 :             Bytes::from_static(b"value 0@0x10"),
    9441           24 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9442           24 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9443           24 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9444           24 :             Bytes::from_static(b"value 4@0x10"),
    9445           24 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9446           24 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9447           24 :             Bytes::from_static(b"value 7@0x10"),
    9448           24 :             Bytes::from_static(b"value 8@0x10"),
    9449           24 :             Bytes::from_static(b"value 9@0x10"),
    9450           24 :         ];
    9451              : 
    9452          264 :         for idx in 0..10 {
    9453          240 :             assert_eq!(
    9454          240 :                 tline
    9455          240 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9456          240 :                     .await
    9457          240 :                     .unwrap(),
    9458          240 :                 &expected_result[idx]
    9459              :             );
    9460          240 :             assert_eq!(
    9461          240 :                 tline
    9462          240 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9463          240 :                     .await
    9464          240 :                     .unwrap(),
    9465          240 :                 &expected_result_at_gc_horizon[idx]
    9466              :             );
    9467              :         }
    9468              : 
    9469           24 :         let cancel = CancellationToken::new();
    9470           24 :         tline
    9471           24 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9472           24 :             .await
    9473           24 :             .unwrap();
    9474              : 
    9475          264 :         for idx in 0..10 {
    9476          240 :             assert_eq!(
    9477          240 :                 tline
    9478          240 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9479          240 :                     .await
    9480          240 :                     .unwrap(),
    9481          240 :                 &expected_result[idx]
    9482              :             );
    9483          240 :             assert_eq!(
    9484          240 :                 tline
    9485          240 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9486          240 :                     .await
    9487          240 :                     .unwrap(),
    9488          240 :                 &expected_result_at_gc_horizon[idx]
    9489              :             );
    9490              :         }
    9491              : 
    9492              :         // increase GC horizon and compact again
    9493              :         {
    9494           24 :             tline
    9495           24 :                 .applied_gc_cutoff_lsn
    9496           24 :                 .lock_for_write()
    9497           24 :                 .store_and_unlock(Lsn(0x40))
    9498           24 :                 .wait()
    9499           24 :                 .await;
    9500              :             // Update GC info
    9501           24 :             let mut guard = tline.gc_info.write().unwrap();
    9502           24 :             guard.cutoffs.time = Lsn(0x40);
    9503           24 :             guard.cutoffs.space = Lsn(0x40);
    9504           24 :         }
    9505           24 :         tline
    9506           24 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9507           24 :             .await
    9508           24 :             .unwrap();
    9509           24 : 
    9510           24 :         Ok(())
    9511           24 :     }
    9512              : 
    9513              :     #[cfg(feature = "testing")]
    9514              :     #[tokio::test]
    9515           12 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9516           12 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9517           12 :         let (tenant, ctx) = harness.load().await;
    9518           12 :         let tline = tenant
    9519           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9520           12 :             .await?;
    9521           12 :         tline.force_advance_lsn(Lsn(0x70));
    9522           12 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9523           12 :         let history = vec![
    9524           12 :             (
    9525           12 :                 key,
    9526           12 :                 Lsn(0x10),
    9527           12 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9528           12 :             ),
    9529           12 :             (
    9530           12 :                 key,
    9531           12 :                 Lsn(0x20),
    9532           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9533           12 :             ),
    9534           12 :             (
    9535           12 :                 key,
    9536           12 :                 Lsn(0x30),
    9537           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9538           12 :             ),
    9539           12 :             (
    9540           12 :                 key,
    9541           12 :                 Lsn(0x40),
    9542           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9543           12 :             ),
    9544           12 :             (
    9545           12 :                 key,
    9546           12 :                 Lsn(0x50),
    9547           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9548           12 :             ),
    9549           12 :             (
    9550           12 :                 key,
    9551           12 :                 Lsn(0x60),
    9552           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9553           12 :             ),
    9554           12 :             (
    9555           12 :                 key,
    9556           12 :                 Lsn(0x70),
    9557           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9558           12 :             ),
    9559           12 :             (
    9560           12 :                 key,
    9561           12 :                 Lsn(0x80),
    9562           12 :                 Value::Image(Bytes::copy_from_slice(
    9563           12 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9564           12 :                 )),
    9565           12 :             ),
    9566           12 :             (
    9567           12 :                 key,
    9568           12 :                 Lsn(0x90),
    9569           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9570           12 :             ),
    9571           12 :         ];
    9572           12 :         let res = tline
    9573           12 :             .generate_key_retention(
    9574           12 :                 key,
    9575           12 :                 &history,
    9576           12 :                 Lsn(0x60),
    9577           12 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9578           12 :                 3,
    9579           12 :                 None,
    9580           12 :                 true,
    9581           12 :             )
    9582           12 :             .await
    9583           12 :             .unwrap();
    9584           12 :         let expected_res = KeyHistoryRetention {
    9585           12 :             below_horizon: vec![
    9586           12 :                 (
    9587           12 :                     Lsn(0x20),
    9588           12 :                     KeyLogAtLsn(vec![(
    9589           12 :                         Lsn(0x20),
    9590           12 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9591           12 :                     )]),
    9592           12 :                 ),
    9593           12 :                 (
    9594           12 :                     Lsn(0x40),
    9595           12 :                     KeyLogAtLsn(vec![
    9596           12 :                         (
    9597           12 :                             Lsn(0x30),
    9598           12 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9599           12 :                         ),
    9600           12 :                         (
    9601           12 :                             Lsn(0x40),
    9602           12 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9603           12 :                         ),
    9604           12 :                     ]),
    9605           12 :                 ),
    9606           12 :                 (
    9607           12 :                     Lsn(0x50),
    9608           12 :                     KeyLogAtLsn(vec![(
    9609           12 :                         Lsn(0x50),
    9610           12 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9611           12 :                     )]),
    9612           12 :                 ),
    9613           12 :                 (
    9614           12 :                     Lsn(0x60),
    9615           12 :                     KeyLogAtLsn(vec![(
    9616           12 :                         Lsn(0x60),
    9617           12 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9618           12 :                     )]),
    9619           12 :                 ),
    9620           12 :             ],
    9621           12 :             above_horizon: KeyLogAtLsn(vec![
    9622           12 :                 (
    9623           12 :                     Lsn(0x70),
    9624           12 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9625           12 :                 ),
    9626           12 :                 (
    9627           12 :                     Lsn(0x80),
    9628           12 :                     Value::Image(Bytes::copy_from_slice(
    9629           12 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9630           12 :                     )),
    9631           12 :                 ),
    9632           12 :                 (
    9633           12 :                     Lsn(0x90),
    9634           12 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9635           12 :                 ),
    9636           12 :             ]),
    9637           12 :         };
    9638           12 :         assert_eq!(res, expected_res);
    9639           12 : 
    9640           12 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9641           12 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9642           12 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9643           12 :         // For example, we have
    9644           12 :         // ```plain
    9645           12 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9646           12 :         // ```
    9647           12 :         // Now the GC horizon moves up, and we have
    9648           12 :         // ```plain
    9649           12 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9650           12 :         // ```
    9651           12 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9652           12 :         // We will end up with
    9653           12 :         // ```plain
    9654           12 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9655           12 :         // ```
    9656           12 :         // Now we run the GC-compaction, and this key does not have a full history.
    9657           12 :         // We should be able to handle this partial history and drop everything before the
    9658           12 :         // gc_horizon image.
    9659           12 : 
    9660           12 :         let history = vec![
    9661           12 :             (
    9662           12 :                 key,
    9663           12 :                 Lsn(0x20),
    9664           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9665           12 :             ),
    9666           12 :             (
    9667           12 :                 key,
    9668           12 :                 Lsn(0x30),
    9669           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9670           12 :             ),
    9671           12 :             (
    9672           12 :                 key,
    9673           12 :                 Lsn(0x40),
    9674           12 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9675           12 :             ),
    9676           12 :             (
    9677           12 :                 key,
    9678           12 :                 Lsn(0x50),
    9679           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9680           12 :             ),
    9681           12 :             (
    9682           12 :                 key,
    9683           12 :                 Lsn(0x60),
    9684           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9685           12 :             ),
    9686           12 :             (
    9687           12 :                 key,
    9688           12 :                 Lsn(0x70),
    9689           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9690           12 :             ),
    9691           12 :             (
    9692           12 :                 key,
    9693           12 :                 Lsn(0x80),
    9694           12 :                 Value::Image(Bytes::copy_from_slice(
    9695           12 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9696           12 :                 )),
    9697           12 :             ),
    9698           12 :             (
    9699           12 :                 key,
    9700           12 :                 Lsn(0x90),
    9701           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9702           12 :             ),
    9703           12 :         ];
    9704           12 :         let res = tline
    9705           12 :             .generate_key_retention(
    9706           12 :                 key,
    9707           12 :                 &history,
    9708           12 :                 Lsn(0x60),
    9709           12 :                 &[Lsn(0x40), Lsn(0x50)],
    9710           12 :                 3,
    9711           12 :                 None,
    9712           12 :                 true,
    9713           12 :             )
    9714           12 :             .await
    9715           12 :             .unwrap();
    9716           12 :         let expected_res = KeyHistoryRetention {
    9717           12 :             below_horizon: vec![
    9718           12 :                 (
    9719           12 :                     Lsn(0x40),
    9720           12 :                     KeyLogAtLsn(vec![(
    9721           12 :                         Lsn(0x40),
    9722           12 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9723           12 :                     )]),
    9724           12 :                 ),
    9725           12 :                 (
    9726           12 :                     Lsn(0x50),
    9727           12 :                     KeyLogAtLsn(vec![(
    9728           12 :                         Lsn(0x50),
    9729           12 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9730           12 :                     )]),
    9731           12 :                 ),
    9732           12 :                 (
    9733           12 :                     Lsn(0x60),
    9734           12 :                     KeyLogAtLsn(vec![(
    9735           12 :                         Lsn(0x60),
    9736           12 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9737           12 :                     )]),
    9738           12 :                 ),
    9739           12 :             ],
    9740           12 :             above_horizon: KeyLogAtLsn(vec![
    9741           12 :                 (
    9742           12 :                     Lsn(0x70),
    9743           12 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9744           12 :                 ),
    9745           12 :                 (
    9746           12 :                     Lsn(0x80),
    9747           12 :                     Value::Image(Bytes::copy_from_slice(
    9748           12 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9749           12 :                     )),
    9750           12 :                 ),
    9751           12 :                 (
    9752           12 :                     Lsn(0x90),
    9753           12 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9754           12 :                 ),
    9755           12 :             ]),
    9756           12 :         };
    9757           12 :         assert_eq!(res, expected_res);
    9758           12 : 
    9759           12 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9760           12 :         // the ancestor image in the test case.
    9761           12 : 
    9762           12 :         let history = vec![
    9763           12 :             (
    9764           12 :                 key,
    9765           12 :                 Lsn(0x20),
    9766           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9767           12 :             ),
    9768           12 :             (
    9769           12 :                 key,
    9770           12 :                 Lsn(0x30),
    9771           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9772           12 :             ),
    9773           12 :             (
    9774           12 :                 key,
    9775           12 :                 Lsn(0x40),
    9776           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9777           12 :             ),
    9778           12 :             (
    9779           12 :                 key,
    9780           12 :                 Lsn(0x70),
    9781           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9782           12 :             ),
    9783           12 :         ];
    9784           12 :         let res = tline
    9785           12 :             .generate_key_retention(
    9786           12 :                 key,
    9787           12 :                 &history,
    9788           12 :                 Lsn(0x60),
    9789           12 :                 &[],
    9790           12 :                 3,
    9791           12 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9792           12 :                 true,
    9793           12 :             )
    9794           12 :             .await
    9795           12 :             .unwrap();
    9796           12 :         let expected_res = KeyHistoryRetention {
    9797           12 :             below_horizon: vec![(
    9798           12 :                 Lsn(0x60),
    9799           12 :                 KeyLogAtLsn(vec![(
    9800           12 :                     Lsn(0x60),
    9801           12 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9802           12 :                 )]),
    9803           12 :             )],
    9804           12 :             above_horizon: KeyLogAtLsn(vec![(
    9805           12 :                 Lsn(0x70),
    9806           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9807           12 :             )]),
    9808           12 :         };
    9809           12 :         assert_eq!(res, expected_res);
    9810           12 : 
    9811           12 :         let history = vec![
    9812           12 :             (
    9813           12 :                 key,
    9814           12 :                 Lsn(0x20),
    9815           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9816           12 :             ),
    9817           12 :             (
    9818           12 :                 key,
    9819           12 :                 Lsn(0x40),
    9820           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9821           12 :             ),
    9822           12 :             (
    9823           12 :                 key,
    9824           12 :                 Lsn(0x60),
    9825           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9826           12 :             ),
    9827           12 :             (
    9828           12 :                 key,
    9829           12 :                 Lsn(0x70),
    9830           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9831           12 :             ),
    9832           12 :         ];
    9833           12 :         let res = tline
    9834           12 :             .generate_key_retention(
    9835           12 :                 key,
    9836           12 :                 &history,
    9837           12 :                 Lsn(0x60),
    9838           12 :                 &[Lsn(0x30)],
    9839           12 :                 3,
    9840           12 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9841           12 :                 true,
    9842           12 :             )
    9843           12 :             .await
    9844           12 :             .unwrap();
    9845           12 :         let expected_res = KeyHistoryRetention {
    9846           12 :             below_horizon: vec![
    9847           12 :                 (
    9848           12 :                     Lsn(0x30),
    9849           12 :                     KeyLogAtLsn(vec![(
    9850           12 :                         Lsn(0x20),
    9851           12 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9852           12 :                     )]),
    9853           12 :                 ),
    9854           12 :                 (
    9855           12 :                     Lsn(0x60),
    9856           12 :                     KeyLogAtLsn(vec![(
    9857           12 :                         Lsn(0x60),
    9858           12 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9859           12 :                     )]),
    9860           12 :                 ),
    9861           12 :             ],
    9862           12 :             above_horizon: KeyLogAtLsn(vec![(
    9863           12 :                 Lsn(0x70),
    9864           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9865           12 :             )]),
    9866           12 :         };
    9867           12 :         assert_eq!(res, expected_res);
    9868           12 : 
    9869           12 :         Ok(())
    9870           12 :     }
    9871              : 
    9872              :     #[cfg(feature = "testing")]
    9873              :     #[tokio::test]
    9874           12 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9875           12 :         let harness =
    9876           12 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9877           12 :         let (tenant, ctx) = harness.load().await;
    9878           12 : 
    9879         3108 :         fn get_key(id: u32) -> Key {
    9880         3108 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9881         3108 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9882         3108 :             key.field6 = id;
    9883         3108 :             key
    9884         3108 :         }
    9885           12 : 
    9886           12 :         let img_layer = (0..10)
    9887          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9888           12 :             .collect_vec();
    9889           12 : 
    9890           12 :         let delta1 = vec![
    9891           12 :             (
    9892           12 :                 get_key(1),
    9893           12 :                 Lsn(0x20),
    9894           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9895           12 :             ),
    9896           12 :             (
    9897           12 :                 get_key(2),
    9898           12 :                 Lsn(0x30),
    9899           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9900           12 :             ),
    9901           12 :             (
    9902           12 :                 get_key(3),
    9903           12 :                 Lsn(0x28),
    9904           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9905           12 :             ),
    9906           12 :             (
    9907           12 :                 get_key(3),
    9908           12 :                 Lsn(0x30),
    9909           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9910           12 :             ),
    9911           12 :             (
    9912           12 :                 get_key(3),
    9913           12 :                 Lsn(0x40),
    9914           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9915           12 :             ),
    9916           12 :         ];
    9917           12 :         let delta2 = vec![
    9918           12 :             (
    9919           12 :                 get_key(5),
    9920           12 :                 Lsn(0x20),
    9921           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9922           12 :             ),
    9923           12 :             (
    9924           12 :                 get_key(6),
    9925           12 :                 Lsn(0x20),
    9926           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9927           12 :             ),
    9928           12 :         ];
    9929           12 :         let delta3 = vec![
    9930           12 :             (
    9931           12 :                 get_key(8),
    9932           12 :                 Lsn(0x48),
    9933           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9934           12 :             ),
    9935           12 :             (
    9936           12 :                 get_key(9),
    9937           12 :                 Lsn(0x48),
    9938           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9939           12 :             ),
    9940           12 :         ];
    9941           12 : 
    9942           12 :         let tline = tenant
    9943           12 :             .create_test_timeline_with_layers(
    9944           12 :                 TIMELINE_ID,
    9945           12 :                 Lsn(0x10),
    9946           12 :                 DEFAULT_PG_VERSION,
    9947           12 :                 &ctx,
    9948           12 :                 Vec::new(), // in-memory layers
    9949           12 :                 vec![
    9950           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9951           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9952           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9953           12 :                 ], // delta layers
    9954           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9955           12 :                 Lsn(0x50),
    9956           12 :             )
    9957           12 :             .await?;
    9958           12 :         {
    9959           12 :             tline
    9960           12 :                 .applied_gc_cutoff_lsn
    9961           12 :                 .lock_for_write()
    9962           12 :                 .store_and_unlock(Lsn(0x30))
    9963           12 :                 .wait()
    9964           12 :                 .await;
    9965           12 :             // Update GC info
    9966           12 :             let mut guard = tline.gc_info.write().unwrap();
    9967           12 :             *guard = GcInfo {
    9968           12 :                 retain_lsns: vec![
    9969           12 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9970           12 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9971           12 :                 ],
    9972           12 :                 cutoffs: GcCutoffs {
    9973           12 :                     time: Lsn(0x30),
    9974           12 :                     space: Lsn(0x30),
    9975           12 :                 },
    9976           12 :                 leases: Default::default(),
    9977           12 :                 within_ancestor_pitr: false,
    9978           12 :             };
    9979           12 :         }
    9980           12 : 
    9981           12 :         let expected_result = [
    9982           12 :             Bytes::from_static(b"value 0@0x10"),
    9983           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9984           12 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9985           12 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9986           12 :             Bytes::from_static(b"value 4@0x10"),
    9987           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9988           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9989           12 :             Bytes::from_static(b"value 7@0x10"),
    9990           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9991           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9992           12 :         ];
    9993           12 : 
    9994           12 :         let expected_result_at_gc_horizon = [
    9995           12 :             Bytes::from_static(b"value 0@0x10"),
    9996           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9997           12 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9998           12 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9999           12 :             Bytes::from_static(b"value 4@0x10"),
   10000           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10001           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10002           12 :             Bytes::from_static(b"value 7@0x10"),
   10003           12 :             Bytes::from_static(b"value 8@0x10"),
   10004           12 :             Bytes::from_static(b"value 9@0x10"),
   10005           12 :         ];
   10006           12 : 
   10007           12 :         let expected_result_at_lsn_20 = [
   10008           12 :             Bytes::from_static(b"value 0@0x10"),
   10009           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10010           12 :             Bytes::from_static(b"value 2@0x10"),
   10011           12 :             Bytes::from_static(b"value 3@0x10"),
   10012           12 :             Bytes::from_static(b"value 4@0x10"),
   10013           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10014           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10015           12 :             Bytes::from_static(b"value 7@0x10"),
   10016           12 :             Bytes::from_static(b"value 8@0x10"),
   10017           12 :             Bytes::from_static(b"value 9@0x10"),
   10018           12 :         ];
   10019           12 : 
   10020           12 :         let expected_result_at_lsn_10 = [
   10021           12 :             Bytes::from_static(b"value 0@0x10"),
   10022           12 :             Bytes::from_static(b"value 1@0x10"),
   10023           12 :             Bytes::from_static(b"value 2@0x10"),
   10024           12 :             Bytes::from_static(b"value 3@0x10"),
   10025           12 :             Bytes::from_static(b"value 4@0x10"),
   10026           12 :             Bytes::from_static(b"value 5@0x10"),
   10027           12 :             Bytes::from_static(b"value 6@0x10"),
   10028           12 :             Bytes::from_static(b"value 7@0x10"),
   10029           12 :             Bytes::from_static(b"value 8@0x10"),
   10030           12 :             Bytes::from_static(b"value 9@0x10"),
   10031           12 :         ];
   10032           12 : 
   10033           72 :         let verify_result = || async {
   10034           72 :             let gc_horizon = {
   10035           72 :                 let gc_info = tline.gc_info.read().unwrap();
   10036           72 :                 gc_info.cutoffs.time
   10037           12 :             };
   10038          792 :             for idx in 0..10 {
   10039          720 :                 assert_eq!(
   10040          720 :                     tline
   10041          720 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10042          720 :                         .await
   10043          720 :                         .unwrap(),
   10044          720 :                     &expected_result[idx]
   10045           12 :                 );
   10046          720 :                 assert_eq!(
   10047          720 :                     tline
   10048          720 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10049          720 :                         .await
   10050          720 :                         .unwrap(),
   10051          720 :                     &expected_result_at_gc_horizon[idx]
   10052           12 :                 );
   10053          720 :                 assert_eq!(
   10054          720 :                     tline
   10055          720 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10056          720 :                         .await
   10057          720 :                         .unwrap(),
   10058          720 :                     &expected_result_at_lsn_20[idx]
   10059           12 :                 );
   10060          720 :                 assert_eq!(
   10061          720 :                     tline
   10062          720 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10063          720 :                         .await
   10064          720 :                         .unwrap(),
   10065          720 :                     &expected_result_at_lsn_10[idx]
   10066           12 :                 );
   10067           12 :             }
   10068          144 :         };
   10069           12 : 
   10070           12 :         verify_result().await;
   10071           12 : 
   10072           12 :         let cancel = CancellationToken::new();
   10073           12 :         let mut dryrun_flags = EnumSet::new();
   10074           12 :         dryrun_flags.insert(CompactFlags::DryRun);
   10075           12 : 
   10076           12 :         tline
   10077           12 :             .compact_with_gc(
   10078           12 :                 &cancel,
   10079           12 :                 CompactOptions {
   10080           12 :                     flags: dryrun_flags,
   10081           12 :                     ..Default::default()
   10082           12 :                 },
   10083           12 :                 &ctx,
   10084           12 :             )
   10085           12 :             .await
   10086           12 :             .unwrap();
   10087           12 :         // 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           12 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10089           12 :         verify_result().await;
   10090           12 : 
   10091           12 :         tline
   10092           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10093           12 :             .await
   10094           12 :             .unwrap();
   10095           12 :         verify_result().await;
   10096           12 : 
   10097           12 :         // compact again
   10098           12 :         tline
   10099           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10100           12 :             .await
   10101           12 :             .unwrap();
   10102           12 :         verify_result().await;
   10103           12 : 
   10104           12 :         // increase GC horizon and compact again
   10105           12 :         {
   10106           12 :             tline
   10107           12 :                 .applied_gc_cutoff_lsn
   10108           12 :                 .lock_for_write()
   10109           12 :                 .store_and_unlock(Lsn(0x38))
   10110           12 :                 .wait()
   10111           12 :                 .await;
   10112           12 :             // Update GC info
   10113           12 :             let mut guard = tline.gc_info.write().unwrap();
   10114           12 :             guard.cutoffs.time = Lsn(0x38);
   10115           12 :             guard.cutoffs.space = Lsn(0x38);
   10116           12 :         }
   10117           12 :         tline
   10118           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10119           12 :             .await
   10120           12 :             .unwrap();
   10121           12 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10122           12 : 
   10123           12 :         // not increasing the GC horizon and compact again
   10124           12 :         tline
   10125           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10126           12 :             .await
   10127           12 :             .unwrap();
   10128           12 :         verify_result().await;
   10129           12 : 
   10130           12 :         Ok(())
   10131           12 :     }
   10132              : 
   10133              :     #[cfg(feature = "testing")]
   10134              :     #[tokio::test]
   10135           12 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10136           12 :     {
   10137           12 :         let harness =
   10138           12 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10139           12 :                 .await?;
   10140           12 :         let (tenant, ctx) = harness.load().await;
   10141           12 : 
   10142         2112 :         fn get_key(id: u32) -> Key {
   10143         2112 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10144         2112 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10145         2112 :             key.field6 = id;
   10146         2112 :             key
   10147         2112 :         }
   10148           12 : 
   10149           12 :         let img_layer = (0..10)
   10150          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10151           12 :             .collect_vec();
   10152           12 : 
   10153           12 :         let delta1 = vec![
   10154           12 :             (
   10155           12 :                 get_key(1),
   10156           12 :                 Lsn(0x20),
   10157           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10158           12 :             ),
   10159           12 :             (
   10160           12 :                 get_key(1),
   10161           12 :                 Lsn(0x28),
   10162           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10163           12 :             ),
   10164           12 :         ];
   10165           12 :         let delta2 = vec![
   10166           12 :             (
   10167           12 :                 get_key(1),
   10168           12 :                 Lsn(0x30),
   10169           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10170           12 :             ),
   10171           12 :             (
   10172           12 :                 get_key(1),
   10173           12 :                 Lsn(0x38),
   10174           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10175           12 :             ),
   10176           12 :         ];
   10177           12 :         let delta3 = vec![
   10178           12 :             (
   10179           12 :                 get_key(8),
   10180           12 :                 Lsn(0x48),
   10181           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10182           12 :             ),
   10183           12 :             (
   10184           12 :                 get_key(9),
   10185           12 :                 Lsn(0x48),
   10186           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10187           12 :             ),
   10188           12 :         ];
   10189           12 : 
   10190           12 :         let tline = tenant
   10191           12 :             .create_test_timeline_with_layers(
   10192           12 :                 TIMELINE_ID,
   10193           12 :                 Lsn(0x10),
   10194           12 :                 DEFAULT_PG_VERSION,
   10195           12 :                 &ctx,
   10196           12 :                 Vec::new(), // in-memory layers
   10197           12 :                 vec![
   10198           12 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10199           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10200           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10201           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10202           12 :                 ], // delta layers
   10203           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10204           12 :                 Lsn(0x50),
   10205           12 :             )
   10206           12 :             .await?;
   10207           12 :         {
   10208           12 :             tline
   10209           12 :                 .applied_gc_cutoff_lsn
   10210           12 :                 .lock_for_write()
   10211           12 :                 .store_and_unlock(Lsn(0x30))
   10212           12 :                 .wait()
   10213           12 :                 .await;
   10214           12 :             // Update GC info
   10215           12 :             let mut guard = tline.gc_info.write().unwrap();
   10216           12 :             *guard = GcInfo {
   10217           12 :                 retain_lsns: vec![
   10218           12 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10219           12 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10220           12 :                 ],
   10221           12 :                 cutoffs: GcCutoffs {
   10222           12 :                     time: Lsn(0x30),
   10223           12 :                     space: Lsn(0x30),
   10224           12 :                 },
   10225           12 :                 leases: Default::default(),
   10226           12 :                 within_ancestor_pitr: false,
   10227           12 :             };
   10228           12 :         }
   10229           12 : 
   10230           12 :         let expected_result = [
   10231           12 :             Bytes::from_static(b"value 0@0x10"),
   10232           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10233           12 :             Bytes::from_static(b"value 2@0x10"),
   10234           12 :             Bytes::from_static(b"value 3@0x10"),
   10235           12 :             Bytes::from_static(b"value 4@0x10"),
   10236           12 :             Bytes::from_static(b"value 5@0x10"),
   10237           12 :             Bytes::from_static(b"value 6@0x10"),
   10238           12 :             Bytes::from_static(b"value 7@0x10"),
   10239           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10240           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10241           12 :         ];
   10242           12 : 
   10243           12 :         let expected_result_at_gc_horizon = [
   10244           12 :             Bytes::from_static(b"value 0@0x10"),
   10245           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10246           12 :             Bytes::from_static(b"value 2@0x10"),
   10247           12 :             Bytes::from_static(b"value 3@0x10"),
   10248           12 :             Bytes::from_static(b"value 4@0x10"),
   10249           12 :             Bytes::from_static(b"value 5@0x10"),
   10250           12 :             Bytes::from_static(b"value 6@0x10"),
   10251           12 :             Bytes::from_static(b"value 7@0x10"),
   10252           12 :             Bytes::from_static(b"value 8@0x10"),
   10253           12 :             Bytes::from_static(b"value 9@0x10"),
   10254           12 :         ];
   10255           12 : 
   10256           12 :         let expected_result_at_lsn_20 = [
   10257           12 :             Bytes::from_static(b"value 0@0x10"),
   10258           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10259           12 :             Bytes::from_static(b"value 2@0x10"),
   10260           12 :             Bytes::from_static(b"value 3@0x10"),
   10261           12 :             Bytes::from_static(b"value 4@0x10"),
   10262           12 :             Bytes::from_static(b"value 5@0x10"),
   10263           12 :             Bytes::from_static(b"value 6@0x10"),
   10264           12 :             Bytes::from_static(b"value 7@0x10"),
   10265           12 :             Bytes::from_static(b"value 8@0x10"),
   10266           12 :             Bytes::from_static(b"value 9@0x10"),
   10267           12 :         ];
   10268           12 : 
   10269           12 :         let expected_result_at_lsn_10 = [
   10270           12 :             Bytes::from_static(b"value 0@0x10"),
   10271           12 :             Bytes::from_static(b"value 1@0x10"),
   10272           12 :             Bytes::from_static(b"value 2@0x10"),
   10273           12 :             Bytes::from_static(b"value 3@0x10"),
   10274           12 :             Bytes::from_static(b"value 4@0x10"),
   10275           12 :             Bytes::from_static(b"value 5@0x10"),
   10276           12 :             Bytes::from_static(b"value 6@0x10"),
   10277           12 :             Bytes::from_static(b"value 7@0x10"),
   10278           12 :             Bytes::from_static(b"value 8@0x10"),
   10279           12 :             Bytes::from_static(b"value 9@0x10"),
   10280           12 :         ];
   10281           12 : 
   10282           48 :         let verify_result = || async {
   10283           48 :             let gc_horizon = {
   10284           48 :                 let gc_info = tline.gc_info.read().unwrap();
   10285           48 :                 gc_info.cutoffs.time
   10286           12 :             };
   10287          528 :             for idx in 0..10 {
   10288          480 :                 assert_eq!(
   10289          480 :                     tline
   10290          480 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10291          480 :                         .await
   10292          480 :                         .unwrap(),
   10293          480 :                     &expected_result[idx]
   10294           12 :                 );
   10295          480 :                 assert_eq!(
   10296          480 :                     tline
   10297          480 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10298          480 :                         .await
   10299          480 :                         .unwrap(),
   10300          480 :                     &expected_result_at_gc_horizon[idx]
   10301           12 :                 );
   10302          480 :                 assert_eq!(
   10303          480 :                     tline
   10304          480 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10305          480 :                         .await
   10306          480 :                         .unwrap(),
   10307          480 :                     &expected_result_at_lsn_20[idx]
   10308           12 :                 );
   10309          480 :                 assert_eq!(
   10310          480 :                     tline
   10311          480 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10312          480 :                         .await
   10313          480 :                         .unwrap(),
   10314          480 :                     &expected_result_at_lsn_10[idx]
   10315           12 :                 );
   10316           12 :             }
   10317           96 :         };
   10318           12 : 
   10319           12 :         verify_result().await;
   10320           12 : 
   10321           12 :         let cancel = CancellationToken::new();
   10322           12 :         let mut dryrun_flags = EnumSet::new();
   10323           12 :         dryrun_flags.insert(CompactFlags::DryRun);
   10324           12 : 
   10325           12 :         tline
   10326           12 :             .compact_with_gc(
   10327           12 :                 &cancel,
   10328           12 :                 CompactOptions {
   10329           12 :                     flags: dryrun_flags,
   10330           12 :                     ..Default::default()
   10331           12 :                 },
   10332           12 :                 &ctx,
   10333           12 :             )
   10334           12 :             .await
   10335           12 :             .unwrap();
   10336           12 :         // 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           12 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10338           12 :         verify_result().await;
   10339           12 : 
   10340           12 :         tline
   10341           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10342           12 :             .await
   10343           12 :             .unwrap();
   10344           12 :         verify_result().await;
   10345           12 : 
   10346           12 :         // compact again
   10347           12 :         tline
   10348           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10349           12 :             .await
   10350           12 :             .unwrap();
   10351           12 :         verify_result().await;
   10352           12 : 
   10353           12 :         Ok(())
   10354           12 :     }
   10355              : 
   10356              :     #[cfg(feature = "testing")]
   10357              :     #[tokio::test]
   10358           12 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10359           12 :         use models::CompactLsnRange;
   10360           12 : 
   10361           12 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10362           12 :         let (tenant, ctx) = harness.load().await;
   10363           12 : 
   10364          996 :         fn get_key(id: u32) -> Key {
   10365          996 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10366          996 :             key.field6 = id;
   10367          996 :             key
   10368          996 :         }
   10369           12 : 
   10370           12 :         let img_layer = (0..10)
   10371          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10372           12 :             .collect_vec();
   10373           12 : 
   10374           12 :         let delta1 = vec![
   10375           12 :             (
   10376           12 :                 get_key(1),
   10377           12 :                 Lsn(0x20),
   10378           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10379           12 :             ),
   10380           12 :             (
   10381           12 :                 get_key(2),
   10382           12 :                 Lsn(0x30),
   10383           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10384           12 :             ),
   10385           12 :             (
   10386           12 :                 get_key(3),
   10387           12 :                 Lsn(0x28),
   10388           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10389           12 :             ),
   10390           12 :             (
   10391           12 :                 get_key(3),
   10392           12 :                 Lsn(0x30),
   10393           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10394           12 :             ),
   10395           12 :             (
   10396           12 :                 get_key(3),
   10397           12 :                 Lsn(0x40),
   10398           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10399           12 :             ),
   10400           12 :         ];
   10401           12 :         let delta2 = vec![
   10402           12 :             (
   10403           12 :                 get_key(5),
   10404           12 :                 Lsn(0x20),
   10405           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10406           12 :             ),
   10407           12 :             (
   10408           12 :                 get_key(6),
   10409           12 :                 Lsn(0x20),
   10410           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10411           12 :             ),
   10412           12 :         ];
   10413           12 :         let delta3 = vec![
   10414           12 :             (
   10415           12 :                 get_key(8),
   10416           12 :                 Lsn(0x48),
   10417           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10418           12 :             ),
   10419           12 :             (
   10420           12 :                 get_key(9),
   10421           12 :                 Lsn(0x48),
   10422           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10423           12 :             ),
   10424           12 :         ];
   10425           12 : 
   10426           12 :         let parent_tline = tenant
   10427           12 :             .create_test_timeline_with_layers(
   10428           12 :                 TIMELINE_ID,
   10429           12 :                 Lsn(0x10),
   10430           12 :                 DEFAULT_PG_VERSION,
   10431           12 :                 &ctx,
   10432           12 :                 vec![],                       // in-memory layers
   10433           12 :                 vec![],                       // delta layers
   10434           12 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10435           12 :                 Lsn(0x18),
   10436           12 :             )
   10437           12 :             .await?;
   10438           12 : 
   10439           12 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10440           12 : 
   10441           12 :         let branch_tline = tenant
   10442           12 :             .branch_timeline_test_with_layers(
   10443           12 :                 &parent_tline,
   10444           12 :                 NEW_TIMELINE_ID,
   10445           12 :                 Some(Lsn(0x18)),
   10446           12 :                 &ctx,
   10447           12 :                 vec![
   10448           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10449           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10450           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10451           12 :                 ], // delta layers
   10452           12 :                 vec![], // image layers
   10453           12 :                 Lsn(0x50),
   10454           12 :             )
   10455           12 :             .await?;
   10456           12 : 
   10457           12 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10458           12 : 
   10459           12 :         {
   10460           12 :             parent_tline
   10461           12 :                 .applied_gc_cutoff_lsn
   10462           12 :                 .lock_for_write()
   10463           12 :                 .store_and_unlock(Lsn(0x10))
   10464           12 :                 .wait()
   10465           12 :                 .await;
   10466           12 :             // Update GC info
   10467           12 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10468           12 :             *guard = GcInfo {
   10469           12 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10470           12 :                 cutoffs: GcCutoffs {
   10471           12 :                     time: Lsn(0x10),
   10472           12 :                     space: Lsn(0x10),
   10473           12 :                 },
   10474           12 :                 leases: Default::default(),
   10475           12 :                 within_ancestor_pitr: false,
   10476           12 :             };
   10477           12 :         }
   10478           12 : 
   10479           12 :         {
   10480           12 :             branch_tline
   10481           12 :                 .applied_gc_cutoff_lsn
   10482           12 :                 .lock_for_write()
   10483           12 :                 .store_and_unlock(Lsn(0x50))
   10484           12 :                 .wait()
   10485           12 :                 .await;
   10486           12 :             // Update GC info
   10487           12 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10488           12 :             *guard = GcInfo {
   10489           12 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10490           12 :                 cutoffs: GcCutoffs {
   10491           12 :                     time: Lsn(0x50),
   10492           12 :                     space: Lsn(0x50),
   10493           12 :                 },
   10494           12 :                 leases: Default::default(),
   10495           12 :                 within_ancestor_pitr: false,
   10496           12 :             };
   10497           12 :         }
   10498           12 : 
   10499           12 :         let expected_result_at_gc_horizon = [
   10500           12 :             Bytes::from_static(b"value 0@0x10"),
   10501           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10502           12 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10503           12 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10504           12 :             Bytes::from_static(b"value 4@0x10"),
   10505           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10506           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10507           12 :             Bytes::from_static(b"value 7@0x10"),
   10508           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10509           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10510           12 :         ];
   10511           12 : 
   10512           12 :         let expected_result_at_lsn_40 = [
   10513           12 :             Bytes::from_static(b"value 0@0x10"),
   10514           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10515           12 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10516           12 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10517           12 :             Bytes::from_static(b"value 4@0x10"),
   10518           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10519           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10520           12 :             Bytes::from_static(b"value 7@0x10"),
   10521           12 :             Bytes::from_static(b"value 8@0x10"),
   10522           12 :             Bytes::from_static(b"value 9@0x10"),
   10523           12 :         ];
   10524           12 : 
   10525           36 :         let verify_result = || async {
   10526          396 :             for idx in 0..10 {
   10527          360 :                 assert_eq!(
   10528          360 :                     branch_tline
   10529          360 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10530          360 :                         .await
   10531          360 :                         .unwrap(),
   10532          360 :                     &expected_result_at_gc_horizon[idx]
   10533           12 :                 );
   10534          360 :                 assert_eq!(
   10535          360 :                     branch_tline
   10536          360 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10537          360 :                         .await
   10538          360 :                         .unwrap(),
   10539          360 :                     &expected_result_at_lsn_40[idx]
   10540           12 :                 );
   10541           12 :             }
   10542           72 :         };
   10543           12 : 
   10544           12 :         verify_result().await;
   10545           12 : 
   10546           12 :         let cancel = CancellationToken::new();
   10547           12 :         branch_tline
   10548           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10549           12 :             .await
   10550           12 :             .unwrap();
   10551           12 : 
   10552           12 :         verify_result().await;
   10553           12 : 
   10554           12 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10555           12 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10556           12 :         branch_tline
   10557           12 :             .compact_with_gc(
   10558           12 :                 &cancel,
   10559           12 :                 CompactOptions {
   10560           12 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10561           12 :                     ..Default::default()
   10562           12 :                 },
   10563           12 :                 &ctx,
   10564           12 :             )
   10565           12 :             .await
   10566           12 :             .unwrap();
   10567           12 : 
   10568           12 :         verify_result().await;
   10569           12 : 
   10570           12 :         Ok(())
   10571           12 :     }
   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           12 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10592           12 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10593           12 :         let (tenant, ctx) = harness.load().await;
   10594           12 : 
   10595           12 :         let will_init_keys = [2, 6];
   10596          264 :         fn get_key(id: u32) -> Key {
   10597          264 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10598          264 :             key.field6 = id;
   10599          264 :             key
   10600          264 :         }
   10601           12 : 
   10602           12 :         let mut expected_key_values = HashMap::new();
   10603           12 : 
   10604           12 :         let baseline_image_layer_lsn = Lsn(0x10);
   10605           12 :         let mut baseline_img_layer = Vec::new();
   10606           72 :         for i in 0..5 {
   10607           60 :             let key = get_key(i);
   10608           60 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10609           60 : 
   10610           60 :             let removed = expected_key_values.insert(key, value.clone());
   10611           60 :             assert!(removed.is_none());
   10612           12 : 
   10613           60 :             baseline_img_layer.push((key, Bytes::from(value)));
   10614           12 :         }
   10615           12 : 
   10616           12 :         let nested_image_layer_lsn = Lsn(0x50);
   10617           12 :         let mut nested_img_layer = Vec::new();
   10618           72 :         for i in 5..10 {
   10619           60 :             let key = get_key(i);
   10620           60 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10621           60 : 
   10622           60 :             let removed = expected_key_values.insert(key, value.clone());
   10623           60 :             assert!(removed.is_none());
   10624           12 : 
   10625           60 :             nested_img_layer.push((key, Bytes::from(value)));
   10626           12 :         }
   10627           12 : 
   10628           12 :         let mut delta_layer_spec = Vec::default();
   10629           12 :         let delta_layer_start_lsn = Lsn(0x20);
   10630           12 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10631           12 : 
   10632          132 :         for i in 0..10 {
   10633          120 :             let key = get_key(i);
   10634          120 :             let key_in_nested = nested_img_layer
   10635          120 :                 .iter()
   10636          480 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10637          120 :             let lsn = {
   10638          120 :                 if key_in_nested {
   10639           60 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10640           12 :                 } else {
   10641           60 :                     delta_layer_start_lsn
   10642           12 :                 }
   10643           12 :             };
   10644           12 : 
   10645          120 :             let will_init = will_init_keys.contains(&i);
   10646          120 :             if will_init {
   10647           24 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10648           24 : 
   10649           24 :                 expected_key_values.insert(key, "".to_string());
   10650           96 :             } else {
   10651           96 :                 let delta = format!("@{lsn}");
   10652           96 :                 delta_layer_spec.push((
   10653           96 :                     key,
   10654           96 :                     lsn,
   10655           96 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10656           96 :                 ));
   10657           96 : 
   10658           96 :                 expected_key_values
   10659           96 :                     .get_mut(&key)
   10660           96 :                     .expect("An image exists for each key")
   10661           96 :                     .push_str(delta.as_str());
   10662           96 :             }
   10663          120 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10664           12 :         }
   10665           12 : 
   10666           12 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10667           12 : 
   10668           12 :         assert!(
   10669           12 :             nested_image_layer_lsn > delta_layer_start_lsn
   10670           12 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10671           12 :         );
   10672           12 : 
   10673           12 :         let tline = tenant
   10674           12 :             .create_test_timeline_with_layers(
   10675           12 :                 TIMELINE_ID,
   10676           12 :                 baseline_image_layer_lsn,
   10677           12 :                 DEFAULT_PG_VERSION,
   10678           12 :                 &ctx,
   10679           12 :                 vec![], // in-memory layers
   10680           12 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10681           12 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10682           12 :                     delta_layer_spec,
   10683           12 :                 )], // delta layers
   10684           12 :                 vec![
   10685           12 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10686           12 :                     (nested_image_layer_lsn, nested_img_layer),
   10687           12 :                 ], // image layers
   10688           12 :                 delta_layer_end_lsn,
   10689           12 :             )
   10690           12 :             .await?;
   10691           12 : 
   10692           12 :         let query = VersionedKeySpaceQuery::uniform(
   10693           12 :             KeySpace::single(get_key(0)..get_key(10)),
   10694           12 :             delta_layer_end_lsn,
   10695           12 :         );
   10696           12 : 
   10697           12 :         let results = tline
   10698           12 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   10699           12 :             .await
   10700           12 :             .expect("No vectored errors");
   10701          132 :         for (key, res) in results {
   10702          120 :             let value = res.expect("No key errors");
   10703          120 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10704          120 :             assert_eq!(value, Bytes::from(expected_value));
   10705           12 :         }
   10706           12 : 
   10707           12 :         Ok(())
   10708           12 :     }
   10709              : 
   10710              :     #[cfg(feature = "testing")]
   10711              :     #[tokio::test]
   10712           12 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   10713           12 :         let harness =
   10714           12 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   10715           12 :         let (tenant, ctx) = harness.load().await;
   10716           12 : 
   10717           12 :         let will_init_keys = [2, 6];
   10718          384 :         fn get_key(id: u32) -> Key {
   10719          384 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10720          384 :             key.field6 = id;
   10721          384 :             key
   10722          384 :         }
   10723           12 : 
   10724           12 :         let mut expected_key_values = HashMap::new();
   10725           12 : 
   10726           12 :         let baseline_image_layer_lsn = Lsn(0x10);
   10727           12 :         let mut baseline_img_layer = Vec::new();
   10728           72 :         for i in 0..5 {
   10729           60 :             let key = get_key(i);
   10730           60 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10731           60 : 
   10732           60 :             let removed = expected_key_values.insert(key, value.clone());
   10733           60 :             assert!(removed.is_none());
   10734           12 : 
   10735           60 :             baseline_img_layer.push((key, Bytes::from(value)));
   10736           12 :         }
   10737           12 : 
   10738           12 :         let nested_image_layer_lsn = Lsn(0x50);
   10739           12 :         let mut nested_img_layer = Vec::new();
   10740           72 :         for i in 5..10 {
   10741           60 :             let key = get_key(i);
   10742           60 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10743           60 : 
   10744           60 :             let removed = expected_key_values.insert(key, value.clone());
   10745           60 :             assert!(removed.is_none());
   10746           12 : 
   10747           60 :             nested_img_layer.push((key, Bytes::from(value)));
   10748           12 :         }
   10749           12 : 
   10750           12 :         let frozen_layer = {
   10751           12 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   10752           12 :             let mut data = Vec::new();
   10753          132 :             for i in 0..10 {
   10754          120 :                 let key = get_key(i);
   10755          120 :                 let key_in_nested = nested_img_layer
   10756          120 :                     .iter()
   10757          480 :                     .any(|(key_with_img, _)| *key_with_img == key);
   10758          120 :                 let lsn = {
   10759          120 :                     if key_in_nested {
   10760           60 :                         Lsn(nested_image_layer_lsn.0 + 5)
   10761           12 :                     } else {
   10762           60 :                         lsn_range.start
   10763           12 :                     }
   10764           12 :                 };
   10765           12 : 
   10766          120 :                 let will_init = will_init_keys.contains(&i);
   10767          120 :                 if will_init {
   10768           24 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10769           24 : 
   10770           24 :                     expected_key_values.insert(key, "".to_string());
   10771           96 :                 } else {
   10772           96 :                     let delta = format!("@{lsn}");
   10773           96 :                     data.push((
   10774           96 :                         key,
   10775           96 :                         lsn,
   10776           96 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10777           96 :                     ));
   10778           96 : 
   10779           96 :                     expected_key_values
   10780           96 :                         .get_mut(&key)
   10781           96 :                         .expect("An image exists for each key")
   10782           96 :                         .push_str(delta.as_str());
   10783           96 :                 }
   10784           12 :             }
   10785           12 : 
   10786           12 :             InMemoryLayerTestDesc {
   10787           12 :                 lsn_range,
   10788           12 :                 is_open: false,
   10789           12 :                 data,
   10790           12 :             }
   10791           12 :         };
   10792           12 : 
   10793           12 :         let (open_layer, last_record_lsn) = {
   10794           12 :             let start_lsn = Lsn(0x70);
   10795           12 :             let mut data = Vec::new();
   10796           12 :             let mut end_lsn = Lsn(0);
   10797          132 :             for i in 0..10 {
   10798          120 :                 let key = get_key(i);
   10799          120 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   10800          120 :                 let delta = format!("@{lsn}");
   10801          120 :                 data.push((
   10802          120 :                     key,
   10803          120 :                     lsn,
   10804          120 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10805          120 :                 ));
   10806          120 : 
   10807          120 :                 expected_key_values
   10808          120 :                     .get_mut(&key)
   10809          120 :                     .expect("An image exists for each key")
   10810          120 :                     .push_str(delta.as_str());
   10811          120 : 
   10812          120 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   10813          120 :             }
   10814           12 : 
   10815           12 :             (
   10816           12 :                 InMemoryLayerTestDesc {
   10817           12 :                     lsn_range: start_lsn..Lsn::MAX,
   10818           12 :                     is_open: true,
   10819           12 :                     data,
   10820           12 :                 },
   10821           12 :                 end_lsn,
   10822           12 :             )
   10823           12 :         };
   10824           12 : 
   10825           12 :         assert!(
   10826           12 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   10827           12 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   10828           12 :         );
   10829           12 : 
   10830           12 :         let tline = tenant
   10831           12 :             .create_test_timeline_with_layers(
   10832           12 :                 TIMELINE_ID,
   10833           12 :                 baseline_image_layer_lsn,
   10834           12 :                 DEFAULT_PG_VERSION,
   10835           12 :                 &ctx,
   10836           12 :                 vec![open_layer, frozen_layer], // in-memory layers
   10837           12 :                 Vec::new(),                     // delta layers
   10838           12 :                 vec![
   10839           12 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10840           12 :                     (nested_image_layer_lsn, nested_img_layer),
   10841           12 :                 ], // image layers
   10842           12 :                 last_record_lsn,
   10843           12 :             )
   10844           12 :             .await?;
   10845           12 : 
   10846           12 :         let query = VersionedKeySpaceQuery::uniform(
   10847           12 :             KeySpace::single(get_key(0)..get_key(10)),
   10848           12 :             last_record_lsn,
   10849           12 :         );
   10850           12 : 
   10851           12 :         let results = tline
   10852           12 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   10853           12 :             .await
   10854           12 :             .expect("No vectored errors");
   10855          132 :         for (key, res) in results {
   10856          120 :             let value = res.expect("No key errors");
   10857          120 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10858          120 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   10859           12 : 
   10860          120 :             tracing::info!("key={key} value={expected_value}");
   10861           12 :         }
   10862           12 : 
   10863           12 :         Ok(())
   10864           12 :     }
   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           12 :     async fn test_read_path() -> anyhow::Result<()> {
   10882           12 :         use rand::seq::SliceRandom;
   10883           12 : 
   10884           12 :         let seed = if cfg!(feature = "fuzz-read-path") {
   10885           12 :             let seed: u64 = thread_rng().r#gen();
   10886            0 :             seed
   10887           12 :         } else {
   10888           12 :             // Use a hard-coded seed when not in fuzzing mode.
   10889           12 :             // Note that with the current approach results are not reproducible
   10890           12 :             // accross platforms and Rust releases.
   10891           12 :             const SEED: u64 = 0;
   10892           12 :             SEED
   10893           12 :         };
   10894           12 : 
   10895           12 :         let mut random = StdRng::seed_from_u64(seed);
   10896           12 : 
   10897           12 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   10898           12 :             const QUERIES: u64 = 5000;
   10899           12 :             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           12 :         } else {
   10904           12 :             const QUERIES: u64 = 1000;
   10905           12 :             const WILL_INIT_CHANCE: u8 = 1;
   10906           12 :             const GAP_CHANCE: u8 = 5;
   10907           12 : 
   10908           12 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   10909           12 :         };
   10910           12 : 
   10911           12 :         let harness = TenantHarness::create("test_read_path").await?;
   10912           12 :         let (tenant, ctx) = harness.load().await;
   10913           12 : 
   10914           12 :         tracing::info!("Using random seed: {seed}");
   10915           12 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   10916           12 : 
   10917           12 :         // Define the layer map shape. Note that this part is not randomized.
   10918           12 : 
   10919           12 :         const KEY_DIMENSION_SIZE: u32 = 99;
   10920           12 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10921           12 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   10922           12 :         let total_key_range = start_key..end_key;
   10923           12 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   10924           12 :         let total_start_lsn = Lsn(104);
   10925           12 :         let last_record_lsn = Lsn(504);
   10926           12 : 
   10927           12 :         assert!(total_key_range_size % 3 == 0);
   10928           12 : 
   10929           12 :         let in_memory_layers_shape = vec![
   10930           12 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   10931           12 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   10932           12 :         ];
   10933           12 : 
   10934           12 :         let delta_layers_shape = vec![
   10935           12 :             (
   10936           12 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   10937           12 :                 Lsn(200)..Lsn(304),
   10938           12 :             ),
   10939           12 :             (
   10940           12 :                 (start_key.add((total_key_range_size / 3) as u32))
   10941           12 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   10942           12 :                 Lsn(200)..Lsn(304),
   10943           12 :             ),
   10944           12 :             (
   10945           12 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   10946           12 :                     ..(start_key.add(total_key_range_size as u32)),
   10947           12 :                 Lsn(200)..Lsn(304),
   10948           12 :             ),
   10949           12 :         ];
   10950           12 : 
   10951           12 :         let image_layers_shape = vec![
   10952           12 :             (
   10953           12 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   10954           12 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   10955           12 :                 Lsn(456),
   10956           12 :             ),
   10957           12 :             (
   10958           12 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   10959           12 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   10960           12 :                 Lsn(256),
   10961           12 :             ),
   10962           12 :             (total_key_range.clone(), total_start_lsn),
   10963           12 :         ];
   10964           12 : 
   10965           12 :         let specification = TestTimelineSpecification {
   10966           12 :             start_lsn: total_start_lsn,
   10967           12 :             last_record_lsn,
   10968           12 :             in_memory_layers_shape,
   10969           12 :             delta_layers_shape,
   10970           12 :             image_layers_shape,
   10971           12 :             gap_chance,
   10972           12 :             will_init_chance,
   10973           12 :         };
   10974           12 : 
   10975           12 :         // Create and randomly fill in the layers according to the specification
   10976           12 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   10977           12 :             &tenant,
   10978           12 :             TIMELINE_ID,
   10979           12 :             DEFAULT_PG_VERSION,
   10980           12 :             specification,
   10981           12 :             &mut random,
   10982           12 :             &ctx,
   10983           12 :         )
   10984           12 :         .await?;
   10985           12 : 
   10986           12 :         // Now generate queries based on the interesting lsns that we've collected.
   10987           12 :         //
   10988           12 :         // While there's still room in the query, pick and interesting LSN and a random
   10989           12 :         // key. Then roll the dice to see if the next key should also be included in
   10990           12 :         // the query. When the roll fails, break the "batch" and pick another point in the
   10991           12 :         // (key, LSN) space.
   10992           12 : 
   10993           12 :         const PICK_NEXT_CHANCE: u8 = 50;
   10994           12 :         for _ in 0..queries {
   10995        12000 :             let query = {
   10996        12000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   10997        12000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   10998           12 : 
   10999       270432 :                 while used_keys.len() < Timeline::MAX_GET_VECTORED_KEYS as usize {
   11000       258432 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11001       258432 :                     let mut selected_key = start_key.add(random.gen_range(0..KEY_DIMENSION_SIZE));
   11002           12 : 
   11003       451368 :                     while used_keys.len() < Timeline::MAX_GET_VECTORED_KEYS as usize {
   11004       445116 :                         if used_keys.contains(&selected_key)
   11005       385848 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11006           12 :                         {
   11007        61116 :                             break;
   11008       384000 :                         }
   11009       384000 : 
   11010       384000 :                         keyspaces_at_lsn
   11011       384000 :                             .entry(*selected_lsn)
   11012       384000 :                             .or_default()
   11013       384000 :                             .add_key(selected_key);
   11014       384000 :                         used_keys.insert(selected_key);
   11015       384000 : 
   11016       384000 :                         let pick_next = random.gen_range(0..=100) <= PICK_NEXT_CHANCE;
   11017       384000 :                         if pick_next {
   11018       192936 :                             selected_key = selected_key.next();
   11019       192936 :                         } else {
   11020       191064 :                             break;
   11021           12 :                         }
   11022           12 :                     }
   11023           12 :                 }
   11024           12 : 
   11025        12000 :                 VersionedKeySpaceQuery::scattered(
   11026        12000 :                     keyspaces_at_lsn
   11027        12000 :                         .into_iter()
   11028       143004 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11029        12000 :                         .collect(),
   11030        12000 :                 )
   11031           12 :             };
   11032           12 : 
   11033           12 :             // Run the query and validate the results
   11034           12 : 
   11035        12000 :             let results = tline
   11036        12000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11037        12000 :                 .await;
   11038           12 : 
   11039        12000 :             let blobs = match results {
   11040        12000 :                 Ok(ok) => ok,
   11041           12 :                 Err(err) => {
   11042            0 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11043           12 :                 }
   11044           12 :             };
   11045           12 : 
   11046       384000 :             for (key, key_res) in blobs.into_iter() {
   11047       384000 :                 match key_res {
   11048       384000 :                     Ok(blob) => {
   11049       384000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11050       384000 :                         let expected = storage.get(key, requested_at_lsn);
   11051       384000 : 
   11052       384000 :                         if blob != expected {
   11053           12 :                             tracing::error!(
   11054           12 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11055           12 :                             );
   11056       384000 :                         }
   11057           12 : 
   11058       384000 :                         assert_eq!(blob, expected);
   11059           12 :                     }
   11060           12 :                     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           12 :                     }
   11067           12 :                 }
   11068           12 :             }
   11069           12 :         }
   11070           12 : 
   11071           12 :         Ok(())
   11072           12 :     }
   11073              : 
   11074         1284 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11075         1284 :         (
   11076         1284 :             k1.is_delta,
   11077         1284 :             k1.key_range.start,
   11078         1284 :             k1.key_range.end,
   11079         1284 :             k1.lsn_range.start,
   11080         1284 :             k1.lsn_range.end,
   11081         1284 :         )
   11082         1284 :             .cmp(&(
   11083         1284 :                 k2.is_delta,
   11084         1284 :                 k2.key_range.start,
   11085         1284 :                 k2.key_range.end,
   11086         1284 :                 k2.lsn_range.start,
   11087         1284 :                 k2.lsn_range.end,
   11088         1284 :             ))
   11089         1284 :     }
   11090              : 
   11091          144 :     async fn inspect_and_sort(
   11092          144 :         tline: &Arc<Timeline>,
   11093          144 :         filter: Option<std::ops::Range<Key>>,
   11094          144 :     ) -> Vec<PersistentLayerKey> {
   11095          144 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11096          144 :         if let Some(filter) = filter {
   11097          648 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11098          132 :         }
   11099          144 :         all_layers.sort_by(sort_layer_key);
   11100          144 :         all_layers
   11101          144 :     }
   11102              : 
   11103              :     #[cfg(feature = "testing")]
   11104          132 :     fn check_layer_map_key_eq(
   11105          132 :         mut left: Vec<PersistentLayerKey>,
   11106          132 :         mut right: Vec<PersistentLayerKey>,
   11107          132 :     ) {
   11108          132 :         left.sort_by(sort_layer_key);
   11109          132 :         right.sort_by(sort_layer_key);
   11110          132 :         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          132 :         }
   11121          132 :     }
   11122              : 
   11123              :     #[cfg(feature = "testing")]
   11124              :     #[tokio::test]
   11125           12 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11126           12 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11127           12 :         let (tenant, ctx) = harness.load().await;
   11128           12 : 
   11129         1092 :         fn get_key(id: u32) -> Key {
   11130         1092 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11131         1092 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11132         1092 :             key.field6 = id;
   11133         1092 :             key
   11134         1092 :         }
   11135           12 : 
   11136           12 :         // img layer at 0x10
   11137           12 :         let img_layer = (0..10)
   11138          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11139           12 :             .collect_vec();
   11140           12 : 
   11141           12 :         let delta1 = vec![
   11142           12 :             (
   11143           12 :                 get_key(1),
   11144           12 :                 Lsn(0x20),
   11145           12 :                 Value::Image(Bytes::from("value 1@0x20")),
   11146           12 :             ),
   11147           12 :             (
   11148           12 :                 get_key(2),
   11149           12 :                 Lsn(0x30),
   11150           12 :                 Value::Image(Bytes::from("value 2@0x30")),
   11151           12 :             ),
   11152           12 :             (
   11153           12 :                 get_key(3),
   11154           12 :                 Lsn(0x40),
   11155           12 :                 Value::Image(Bytes::from("value 3@0x40")),
   11156           12 :             ),
   11157           12 :         ];
   11158           12 :         let delta2 = vec![
   11159           12 :             (
   11160           12 :                 get_key(5),
   11161           12 :                 Lsn(0x20),
   11162           12 :                 Value::Image(Bytes::from("value 5@0x20")),
   11163           12 :             ),
   11164           12 :             (
   11165           12 :                 get_key(6),
   11166           12 :                 Lsn(0x20),
   11167           12 :                 Value::Image(Bytes::from("value 6@0x20")),
   11168           12 :             ),
   11169           12 :         ];
   11170           12 :         let delta3 = vec![
   11171           12 :             (
   11172           12 :                 get_key(8),
   11173           12 :                 Lsn(0x48),
   11174           12 :                 Value::Image(Bytes::from("value 8@0x48")),
   11175           12 :             ),
   11176           12 :             (
   11177           12 :                 get_key(9),
   11178           12 :                 Lsn(0x48),
   11179           12 :                 Value::Image(Bytes::from("value 9@0x48")),
   11180           12 :             ),
   11181           12 :         ];
   11182           12 : 
   11183           12 :         let tline = tenant
   11184           12 :             .create_test_timeline_with_layers(
   11185           12 :                 TIMELINE_ID,
   11186           12 :                 Lsn(0x10),
   11187           12 :                 DEFAULT_PG_VERSION,
   11188           12 :                 &ctx,
   11189           12 :                 vec![], // in-memory layers
   11190           12 :                 vec![
   11191           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11192           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11193           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11194           12 :                 ], // delta layers
   11195           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11196           12 :                 Lsn(0x50),
   11197           12 :             )
   11198           12 :             .await?;
   11199           12 : 
   11200           12 :         {
   11201           12 :             tline
   11202           12 :                 .applied_gc_cutoff_lsn
   11203           12 :                 .lock_for_write()
   11204           12 :                 .store_and_unlock(Lsn(0x30))
   11205           12 :                 .wait()
   11206           12 :                 .await;
   11207           12 :             // Update GC info
   11208           12 :             let mut guard = tline.gc_info.write().unwrap();
   11209           12 :             *guard = GcInfo {
   11210           12 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11211           12 :                 cutoffs: GcCutoffs {
   11212           12 :                     time: Lsn(0x30),
   11213           12 :                     space: Lsn(0x30),
   11214           12 :                 },
   11215           12 :                 leases: Default::default(),
   11216           12 :                 within_ancestor_pitr: false,
   11217           12 :             };
   11218           12 :         }
   11219           12 : 
   11220           12 :         let cancel = CancellationToken::new();
   11221           12 : 
   11222           12 :         // Do a partial compaction on key range 0..2
   11223           12 :         tline
   11224           12 :             .compact_with_gc(
   11225           12 :                 &cancel,
   11226           12 :                 CompactOptions {
   11227           12 :                     flags: EnumSet::new(),
   11228           12 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11229           12 :                     ..Default::default()
   11230           12 :                 },
   11231           12 :                 &ctx,
   11232           12 :             )
   11233           12 :             .await
   11234           12 :             .unwrap();
   11235           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11236           12 :         check_layer_map_key_eq(
   11237           12 :             all_layers,
   11238           12 :             vec![
   11239           12 :                 // newly-generated image layer for the partial compaction range 0-2
   11240           12 :                 PersistentLayerKey {
   11241           12 :                     key_range: get_key(0)..get_key(2),
   11242           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11243           12 :                     is_delta: false,
   11244           12 :                 },
   11245           12 :                 PersistentLayerKey {
   11246           12 :                     key_range: get_key(0)..get_key(10),
   11247           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11248           12 :                     is_delta: false,
   11249           12 :                 },
   11250           12 :                 // delta1 is split and the second part is rewritten
   11251           12 :                 PersistentLayerKey {
   11252           12 :                     key_range: get_key(2)..get_key(4),
   11253           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11254           12 :                     is_delta: true,
   11255           12 :                 },
   11256           12 :                 PersistentLayerKey {
   11257           12 :                     key_range: get_key(5)..get_key(7),
   11258           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11259           12 :                     is_delta: true,
   11260           12 :                 },
   11261           12 :                 PersistentLayerKey {
   11262           12 :                     key_range: get_key(8)..get_key(10),
   11263           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11264           12 :                     is_delta: true,
   11265           12 :                 },
   11266           12 :             ],
   11267           12 :         );
   11268           12 : 
   11269           12 :         // Do a partial compaction on key range 2..4
   11270           12 :         tline
   11271           12 :             .compact_with_gc(
   11272           12 :                 &cancel,
   11273           12 :                 CompactOptions {
   11274           12 :                     flags: EnumSet::new(),
   11275           12 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11276           12 :                     ..Default::default()
   11277           12 :                 },
   11278           12 :                 &ctx,
   11279           12 :             )
   11280           12 :             .await
   11281           12 :             .unwrap();
   11282           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11283           12 :         check_layer_map_key_eq(
   11284           12 :             all_layers,
   11285           12 :             vec![
   11286           12 :                 PersistentLayerKey {
   11287           12 :                     key_range: get_key(0)..get_key(2),
   11288           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11289           12 :                     is_delta: false,
   11290           12 :                 },
   11291           12 :                 PersistentLayerKey {
   11292           12 :                     key_range: get_key(0)..get_key(10),
   11293           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11294           12 :                     is_delta: false,
   11295           12 :                 },
   11296           12 :                 // image layer generated for the compaction range 2-4
   11297           12 :                 PersistentLayerKey {
   11298           12 :                     key_range: get_key(2)..get_key(4),
   11299           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11300           12 :                     is_delta: false,
   11301           12 :                 },
   11302           12 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11303           12 :                 PersistentLayerKey {
   11304           12 :                     key_range: get_key(2)..get_key(4),
   11305           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11306           12 :                     is_delta: true,
   11307           12 :                 },
   11308           12 :                 PersistentLayerKey {
   11309           12 :                     key_range: get_key(5)..get_key(7),
   11310           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11311           12 :                     is_delta: true,
   11312           12 :                 },
   11313           12 :                 PersistentLayerKey {
   11314           12 :                     key_range: get_key(8)..get_key(10),
   11315           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11316           12 :                     is_delta: true,
   11317           12 :                 },
   11318           12 :             ],
   11319           12 :         );
   11320           12 : 
   11321           12 :         // Do a partial compaction on key range 4..9
   11322           12 :         tline
   11323           12 :             .compact_with_gc(
   11324           12 :                 &cancel,
   11325           12 :                 CompactOptions {
   11326           12 :                     flags: EnumSet::new(),
   11327           12 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11328           12 :                     ..Default::default()
   11329           12 :                 },
   11330           12 :                 &ctx,
   11331           12 :             )
   11332           12 :             .await
   11333           12 :             .unwrap();
   11334           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11335           12 :         check_layer_map_key_eq(
   11336           12 :             all_layers,
   11337           12 :             vec![
   11338           12 :                 PersistentLayerKey {
   11339           12 :                     key_range: get_key(0)..get_key(2),
   11340           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11341           12 :                     is_delta: false,
   11342           12 :                 },
   11343           12 :                 PersistentLayerKey {
   11344           12 :                     key_range: get_key(0)..get_key(10),
   11345           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11346           12 :                     is_delta: false,
   11347           12 :                 },
   11348           12 :                 PersistentLayerKey {
   11349           12 :                     key_range: get_key(2)..get_key(4),
   11350           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11351           12 :                     is_delta: false,
   11352           12 :                 },
   11353           12 :                 PersistentLayerKey {
   11354           12 :                     key_range: get_key(2)..get_key(4),
   11355           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11356           12 :                     is_delta: true,
   11357           12 :                 },
   11358           12 :                 // image layer generated for this compaction range
   11359           12 :                 PersistentLayerKey {
   11360           12 :                     key_range: get_key(4)..get_key(9),
   11361           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11362           12 :                     is_delta: false,
   11363           12 :                 },
   11364           12 :                 PersistentLayerKey {
   11365           12 :                     key_range: get_key(8)..get_key(10),
   11366           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11367           12 :                     is_delta: true,
   11368           12 :                 },
   11369           12 :             ],
   11370           12 :         );
   11371           12 : 
   11372           12 :         // Do a partial compaction on key range 9..10
   11373           12 :         tline
   11374           12 :             .compact_with_gc(
   11375           12 :                 &cancel,
   11376           12 :                 CompactOptions {
   11377           12 :                     flags: EnumSet::new(),
   11378           12 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11379           12 :                     ..Default::default()
   11380           12 :                 },
   11381           12 :                 &ctx,
   11382           12 :             )
   11383           12 :             .await
   11384           12 :             .unwrap();
   11385           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11386           12 :         check_layer_map_key_eq(
   11387           12 :             all_layers,
   11388           12 :             vec![
   11389           12 :                 PersistentLayerKey {
   11390           12 :                     key_range: get_key(0)..get_key(2),
   11391           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11392           12 :                     is_delta: false,
   11393           12 :                 },
   11394           12 :                 PersistentLayerKey {
   11395           12 :                     key_range: get_key(0)..get_key(10),
   11396           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11397           12 :                     is_delta: false,
   11398           12 :                 },
   11399           12 :                 PersistentLayerKey {
   11400           12 :                     key_range: get_key(2)..get_key(4),
   11401           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11402           12 :                     is_delta: false,
   11403           12 :                 },
   11404           12 :                 PersistentLayerKey {
   11405           12 :                     key_range: get_key(2)..get_key(4),
   11406           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11407           12 :                     is_delta: true,
   11408           12 :                 },
   11409           12 :                 PersistentLayerKey {
   11410           12 :                     key_range: get_key(4)..get_key(9),
   11411           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11412           12 :                     is_delta: false,
   11413           12 :                 },
   11414           12 :                 // image layer generated for the compaction range
   11415           12 :                 PersistentLayerKey {
   11416           12 :                     key_range: get_key(9)..get_key(10),
   11417           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11418           12 :                     is_delta: false,
   11419           12 :                 },
   11420           12 :                 PersistentLayerKey {
   11421           12 :                     key_range: get_key(8)..get_key(10),
   11422           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11423           12 :                     is_delta: true,
   11424           12 :                 },
   11425           12 :             ],
   11426           12 :         );
   11427           12 : 
   11428           12 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11429           12 :         tline
   11430           12 :             .compact_with_gc(
   11431           12 :                 &cancel,
   11432           12 :                 CompactOptions {
   11433           12 :                     flags: EnumSet::new(),
   11434           12 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11435           12 :                     ..Default::default()
   11436           12 :                 },
   11437           12 :                 &ctx,
   11438           12 :             )
   11439           12 :             .await
   11440           12 :             .unwrap();
   11441           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11442           12 :         check_layer_map_key_eq(
   11443           12 :             all_layers,
   11444           12 :             vec![
   11445           12 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11446           12 :                 PersistentLayerKey {
   11447           12 :                     key_range: get_key(0)..get_key(10),
   11448           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11449           12 :                     is_delta: false,
   11450           12 :                 },
   11451           12 :                 PersistentLayerKey {
   11452           12 :                     key_range: get_key(2)..get_key(4),
   11453           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11454           12 :                     is_delta: true,
   11455           12 :                 },
   11456           12 :                 PersistentLayerKey {
   11457           12 :                     key_range: get_key(8)..get_key(10),
   11458           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11459           12 :                     is_delta: true,
   11460           12 :                 },
   11461           12 :             ],
   11462           12 :         );
   11463           12 :         Ok(())
   11464           12 :     }
   11465              : 
   11466              :     #[cfg(feature = "testing")]
   11467              :     #[tokio::test]
   11468           12 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11469           12 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11470           12 :             .await
   11471           12 :             .unwrap();
   11472           12 :         let (tenant, ctx) = harness.load().await;
   11473           12 :         let tline_parent = tenant
   11474           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11475           12 :             .await
   11476           12 :             .unwrap();
   11477           12 :         let tline_child = tenant
   11478           12 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11479           12 :             .await
   11480           12 :             .unwrap();
   11481           12 :         {
   11482           12 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11483           12 :             assert_eq!(
   11484           12 :                 gc_info_parent.retain_lsns,
   11485           12 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11486           12 :             );
   11487           12 :         }
   11488           12 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11489           12 :         tline_child
   11490           12 :             .remote_client
   11491           12 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11492           12 :             .unwrap();
   11493           12 :         tline_child.remote_client.wait_completion().await.unwrap();
   11494           12 :         offload_timeline(&tenant, &tline_child)
   11495           12 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11496           12 :             .await.unwrap();
   11497           12 :         let child_timeline_id = tline_child.timeline_id;
   11498           12 :         Arc::try_unwrap(tline_child).unwrap();
   11499           12 : 
   11500           12 :         {
   11501           12 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11502           12 :             assert_eq!(
   11503           12 :                 gc_info_parent.retain_lsns,
   11504           12 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11505           12 :             );
   11506           12 :         }
   11507           12 : 
   11508           12 :         tenant
   11509           12 :             .get_offloaded_timeline(child_timeline_id)
   11510           12 :             .unwrap()
   11511           12 :             .defuse_for_tenant_drop();
   11512           12 : 
   11513           12 :         Ok(())
   11514           12 :     }
   11515              : 
   11516              :     #[cfg(feature = "testing")]
   11517              :     #[tokio::test]
   11518           12 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11519           12 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11520           12 :         let (tenant, ctx) = harness.load().await;
   11521           12 : 
   11522         1776 :         fn get_key(id: u32) -> Key {
   11523         1776 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11524         1776 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11525         1776 :             key.field6 = id;
   11526         1776 :             key
   11527         1776 :         }
   11528           12 : 
   11529           12 :         let img_layer = (0..10)
   11530          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11531           12 :             .collect_vec();
   11532           12 : 
   11533           12 :         let delta1 = vec![(
   11534           12 :             get_key(1),
   11535           12 :             Lsn(0x20),
   11536           12 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11537           12 :         )];
   11538           12 :         let delta4 = vec![(
   11539           12 :             get_key(1),
   11540           12 :             Lsn(0x28),
   11541           12 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11542           12 :         )];
   11543           12 :         let delta2 = vec![
   11544           12 :             (
   11545           12 :                 get_key(1),
   11546           12 :                 Lsn(0x30),
   11547           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11548           12 :             ),
   11549           12 :             (
   11550           12 :                 get_key(1),
   11551           12 :                 Lsn(0x38),
   11552           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11553           12 :             ),
   11554           12 :         ];
   11555           12 :         let delta3 = vec![
   11556           12 :             (
   11557           12 :                 get_key(8),
   11558           12 :                 Lsn(0x48),
   11559           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11560           12 :             ),
   11561           12 :             (
   11562           12 :                 get_key(9),
   11563           12 :                 Lsn(0x48),
   11564           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11565           12 :             ),
   11566           12 :         ];
   11567           12 : 
   11568           12 :         let tline = tenant
   11569           12 :             .create_test_timeline_with_layers(
   11570           12 :                 TIMELINE_ID,
   11571           12 :                 Lsn(0x10),
   11572           12 :                 DEFAULT_PG_VERSION,
   11573           12 :                 &ctx,
   11574           12 :                 vec![], // in-memory layers
   11575           12 :                 vec![
   11576           12 :                     // delta1/2/4 only contain a single key but multiple updates
   11577           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11578           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11579           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11580           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11581           12 :                 ], // delta layers
   11582           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11583           12 :                 Lsn(0x50),
   11584           12 :             )
   11585           12 :             .await?;
   11586           12 :         {
   11587           12 :             tline
   11588           12 :                 .applied_gc_cutoff_lsn
   11589           12 :                 .lock_for_write()
   11590           12 :                 .store_and_unlock(Lsn(0x30))
   11591           12 :                 .wait()
   11592           12 :                 .await;
   11593           12 :             // Update GC info
   11594           12 :             let mut guard = tline.gc_info.write().unwrap();
   11595           12 :             *guard = GcInfo {
   11596           12 :                 retain_lsns: vec![
   11597           12 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11598           12 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11599           12 :                 ],
   11600           12 :                 cutoffs: GcCutoffs {
   11601           12 :                     time: Lsn(0x30),
   11602           12 :                     space: Lsn(0x30),
   11603           12 :                 },
   11604           12 :                 leases: Default::default(),
   11605           12 :                 within_ancestor_pitr: false,
   11606           12 :             };
   11607           12 :         }
   11608           12 : 
   11609           12 :         let expected_result = [
   11610           12 :             Bytes::from_static(b"value 0@0x10"),
   11611           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11612           12 :             Bytes::from_static(b"value 2@0x10"),
   11613           12 :             Bytes::from_static(b"value 3@0x10"),
   11614           12 :             Bytes::from_static(b"value 4@0x10"),
   11615           12 :             Bytes::from_static(b"value 5@0x10"),
   11616           12 :             Bytes::from_static(b"value 6@0x10"),
   11617           12 :             Bytes::from_static(b"value 7@0x10"),
   11618           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11619           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11620           12 :         ];
   11621           12 : 
   11622           12 :         let expected_result_at_gc_horizon = [
   11623           12 :             Bytes::from_static(b"value 0@0x10"),
   11624           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11625           12 :             Bytes::from_static(b"value 2@0x10"),
   11626           12 :             Bytes::from_static(b"value 3@0x10"),
   11627           12 :             Bytes::from_static(b"value 4@0x10"),
   11628           12 :             Bytes::from_static(b"value 5@0x10"),
   11629           12 :             Bytes::from_static(b"value 6@0x10"),
   11630           12 :             Bytes::from_static(b"value 7@0x10"),
   11631           12 :             Bytes::from_static(b"value 8@0x10"),
   11632           12 :             Bytes::from_static(b"value 9@0x10"),
   11633           12 :         ];
   11634           12 : 
   11635           12 :         let expected_result_at_lsn_20 = [
   11636           12 :             Bytes::from_static(b"value 0@0x10"),
   11637           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11638           12 :             Bytes::from_static(b"value 2@0x10"),
   11639           12 :             Bytes::from_static(b"value 3@0x10"),
   11640           12 :             Bytes::from_static(b"value 4@0x10"),
   11641           12 :             Bytes::from_static(b"value 5@0x10"),
   11642           12 :             Bytes::from_static(b"value 6@0x10"),
   11643           12 :             Bytes::from_static(b"value 7@0x10"),
   11644           12 :             Bytes::from_static(b"value 8@0x10"),
   11645           12 :             Bytes::from_static(b"value 9@0x10"),
   11646           12 :         ];
   11647           12 : 
   11648           12 :         let expected_result_at_lsn_10 = [
   11649           12 :             Bytes::from_static(b"value 0@0x10"),
   11650           12 :             Bytes::from_static(b"value 1@0x10"),
   11651           12 :             Bytes::from_static(b"value 2@0x10"),
   11652           12 :             Bytes::from_static(b"value 3@0x10"),
   11653           12 :             Bytes::from_static(b"value 4@0x10"),
   11654           12 :             Bytes::from_static(b"value 5@0x10"),
   11655           12 :             Bytes::from_static(b"value 6@0x10"),
   11656           12 :             Bytes::from_static(b"value 7@0x10"),
   11657           12 :             Bytes::from_static(b"value 8@0x10"),
   11658           12 :             Bytes::from_static(b"value 9@0x10"),
   11659           12 :         ];
   11660           12 : 
   11661           36 :         let verify_result = || async {
   11662           36 :             let gc_horizon = {
   11663           36 :                 let gc_info = tline.gc_info.read().unwrap();
   11664           36 :                 gc_info.cutoffs.time
   11665           12 :             };
   11666          396 :             for idx in 0..10 {
   11667          360 :                 assert_eq!(
   11668          360 :                     tline
   11669          360 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11670          360 :                         .await
   11671          360 :                         .unwrap(),
   11672          360 :                     &expected_result[idx]
   11673           12 :                 );
   11674          360 :                 assert_eq!(
   11675          360 :                     tline
   11676          360 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11677          360 :                         .await
   11678          360 :                         .unwrap(),
   11679          360 :                     &expected_result_at_gc_horizon[idx]
   11680           12 :                 );
   11681          360 :                 assert_eq!(
   11682          360 :                     tline
   11683          360 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11684          360 :                         .await
   11685          360 :                         .unwrap(),
   11686          360 :                     &expected_result_at_lsn_20[idx]
   11687           12 :                 );
   11688          360 :                 assert_eq!(
   11689          360 :                     tline
   11690          360 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11691          360 :                         .await
   11692          360 :                         .unwrap(),
   11693          360 :                     &expected_result_at_lsn_10[idx]
   11694           12 :                 );
   11695           12 :             }
   11696           72 :         };
   11697           12 : 
   11698           12 :         verify_result().await;
   11699           12 : 
   11700           12 :         let cancel = CancellationToken::new();
   11701           12 :         tline
   11702           12 :             .compact_with_gc(
   11703           12 :                 &cancel,
   11704           12 :                 CompactOptions {
   11705           12 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   11706           12 :                     ..Default::default()
   11707           12 :                 },
   11708           12 :                 &ctx,
   11709           12 :             )
   11710           12 :             .await
   11711           12 :             .unwrap();
   11712           12 :         verify_result().await;
   11713           12 : 
   11714           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11715           12 :         check_layer_map_key_eq(
   11716           12 :             all_layers,
   11717           12 :             vec![
   11718           12 :                 // The original image layer, not compacted
   11719           12 :                 PersistentLayerKey {
   11720           12 :                     key_range: get_key(0)..get_key(10),
   11721           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11722           12 :                     is_delta: false,
   11723           12 :                 },
   11724           12 :                 // Delta layer below the specified above_lsn not compacted
   11725           12 :                 PersistentLayerKey {
   11726           12 :                     key_range: get_key(1)..get_key(2),
   11727           12 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   11728           12 :                     is_delta: true,
   11729           12 :                 },
   11730           12 :                 // Delta layer compacted above the LSN
   11731           12 :                 PersistentLayerKey {
   11732           12 :                     key_range: get_key(1)..get_key(10),
   11733           12 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   11734           12 :                     is_delta: true,
   11735           12 :                 },
   11736           12 :             ],
   11737           12 :         );
   11738           12 : 
   11739           12 :         // compact again
   11740           12 :         tline
   11741           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11742           12 :             .await
   11743           12 :             .unwrap();
   11744           12 :         verify_result().await;
   11745           12 : 
   11746           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11747           12 :         check_layer_map_key_eq(
   11748           12 :             all_layers,
   11749           12 :             vec![
   11750           12 :                 // The compacted image layer (full key range)
   11751           12 :                 PersistentLayerKey {
   11752           12 :                     key_range: Key::MIN..Key::MAX,
   11753           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11754           12 :                     is_delta: false,
   11755           12 :                 },
   11756           12 :                 // All other data in the delta layer
   11757           12 :                 PersistentLayerKey {
   11758           12 :                     key_range: get_key(1)..get_key(10),
   11759           12 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11760           12 :                     is_delta: true,
   11761           12 :                 },
   11762           12 :             ],
   11763           12 :         );
   11764           12 : 
   11765           12 :         Ok(())
   11766           12 :     }
   11767              : 
   11768              :     #[cfg(feature = "testing")]
   11769              :     #[tokio::test]
   11770           12 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   11771           12 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   11772           12 :         let (tenant, ctx) = harness.load().await;
   11773           12 : 
   11774         3048 :         fn get_key(id: u32) -> Key {
   11775         3048 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11776         3048 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11777         3048 :             key.field6 = id;
   11778         3048 :             key
   11779         3048 :         }
   11780           12 : 
   11781           12 :         let img_layer = (0..10)
   11782          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11783           12 :             .collect_vec();
   11784           12 : 
   11785           12 :         let delta1 = vec![(
   11786           12 :             get_key(1),
   11787           12 :             Lsn(0x20),
   11788           12 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11789           12 :         )];
   11790           12 :         let delta4 = vec![(
   11791           12 :             get_key(1),
   11792           12 :             Lsn(0x28),
   11793           12 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11794           12 :         )];
   11795           12 :         let delta2 = vec![
   11796           12 :             (
   11797           12 :                 get_key(1),
   11798           12 :                 Lsn(0x30),
   11799           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11800           12 :             ),
   11801           12 :             (
   11802           12 :                 get_key(1),
   11803           12 :                 Lsn(0x38),
   11804           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11805           12 :             ),
   11806           12 :         ];
   11807           12 :         let delta3 = vec![
   11808           12 :             (
   11809           12 :                 get_key(8),
   11810           12 :                 Lsn(0x48),
   11811           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11812           12 :             ),
   11813           12 :             (
   11814           12 :                 get_key(9),
   11815           12 :                 Lsn(0x48),
   11816           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11817           12 :             ),
   11818           12 :         ];
   11819           12 : 
   11820           12 :         let tline = tenant
   11821           12 :             .create_test_timeline_with_layers(
   11822           12 :                 TIMELINE_ID,
   11823           12 :                 Lsn(0x10),
   11824           12 :                 DEFAULT_PG_VERSION,
   11825           12 :                 &ctx,
   11826           12 :                 vec![], // in-memory layers
   11827           12 :                 vec![
   11828           12 :                     // delta1/2/4 only contain a single key but multiple updates
   11829           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11830           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11831           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11832           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11833           12 :                 ], // delta layers
   11834           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11835           12 :                 Lsn(0x50),
   11836           12 :             )
   11837           12 :             .await?;
   11838           12 :         {
   11839           12 :             tline
   11840           12 :                 .applied_gc_cutoff_lsn
   11841           12 :                 .lock_for_write()
   11842           12 :                 .store_and_unlock(Lsn(0x30))
   11843           12 :                 .wait()
   11844           12 :                 .await;
   11845           12 :             // Update GC info
   11846           12 :             let mut guard = tline.gc_info.write().unwrap();
   11847           12 :             *guard = GcInfo {
   11848           12 :                 retain_lsns: vec![
   11849           12 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11850           12 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11851           12 :                 ],
   11852           12 :                 cutoffs: GcCutoffs {
   11853           12 :                     time: Lsn(0x30),
   11854           12 :                     space: Lsn(0x30),
   11855           12 :                 },
   11856           12 :                 leases: Default::default(),
   11857           12 :                 within_ancestor_pitr: false,
   11858           12 :             };
   11859           12 :         }
   11860           12 : 
   11861           12 :         let expected_result = [
   11862           12 :             Bytes::from_static(b"value 0@0x10"),
   11863           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11864           12 :             Bytes::from_static(b"value 2@0x10"),
   11865           12 :             Bytes::from_static(b"value 3@0x10"),
   11866           12 :             Bytes::from_static(b"value 4@0x10"),
   11867           12 :             Bytes::from_static(b"value 5@0x10"),
   11868           12 :             Bytes::from_static(b"value 6@0x10"),
   11869           12 :             Bytes::from_static(b"value 7@0x10"),
   11870           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11871           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11872           12 :         ];
   11873           12 : 
   11874           12 :         let expected_result_at_gc_horizon = [
   11875           12 :             Bytes::from_static(b"value 0@0x10"),
   11876           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11877           12 :             Bytes::from_static(b"value 2@0x10"),
   11878           12 :             Bytes::from_static(b"value 3@0x10"),
   11879           12 :             Bytes::from_static(b"value 4@0x10"),
   11880           12 :             Bytes::from_static(b"value 5@0x10"),
   11881           12 :             Bytes::from_static(b"value 6@0x10"),
   11882           12 :             Bytes::from_static(b"value 7@0x10"),
   11883           12 :             Bytes::from_static(b"value 8@0x10"),
   11884           12 :             Bytes::from_static(b"value 9@0x10"),
   11885           12 :         ];
   11886           12 : 
   11887           12 :         let expected_result_at_lsn_20 = [
   11888           12 :             Bytes::from_static(b"value 0@0x10"),
   11889           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11890           12 :             Bytes::from_static(b"value 2@0x10"),
   11891           12 :             Bytes::from_static(b"value 3@0x10"),
   11892           12 :             Bytes::from_static(b"value 4@0x10"),
   11893           12 :             Bytes::from_static(b"value 5@0x10"),
   11894           12 :             Bytes::from_static(b"value 6@0x10"),
   11895           12 :             Bytes::from_static(b"value 7@0x10"),
   11896           12 :             Bytes::from_static(b"value 8@0x10"),
   11897           12 :             Bytes::from_static(b"value 9@0x10"),
   11898           12 :         ];
   11899           12 : 
   11900           12 :         let expected_result_at_lsn_10 = [
   11901           12 :             Bytes::from_static(b"value 0@0x10"),
   11902           12 :             Bytes::from_static(b"value 1@0x10"),
   11903           12 :             Bytes::from_static(b"value 2@0x10"),
   11904           12 :             Bytes::from_static(b"value 3@0x10"),
   11905           12 :             Bytes::from_static(b"value 4@0x10"),
   11906           12 :             Bytes::from_static(b"value 5@0x10"),
   11907           12 :             Bytes::from_static(b"value 6@0x10"),
   11908           12 :             Bytes::from_static(b"value 7@0x10"),
   11909           12 :             Bytes::from_static(b"value 8@0x10"),
   11910           12 :             Bytes::from_static(b"value 9@0x10"),
   11911           12 :         ];
   11912           12 : 
   11913           60 :         let verify_result = || async {
   11914           60 :             let gc_horizon = {
   11915           60 :                 let gc_info = tline.gc_info.read().unwrap();
   11916           60 :                 gc_info.cutoffs.time
   11917           12 :             };
   11918          660 :             for idx in 0..10 {
   11919          600 :                 assert_eq!(
   11920          600 :                     tline
   11921          600 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11922          600 :                         .await
   11923          600 :                         .unwrap(),
   11924          600 :                     &expected_result[idx]
   11925           12 :                 );
   11926          600 :                 assert_eq!(
   11927          600 :                     tline
   11928          600 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11929          600 :                         .await
   11930          600 :                         .unwrap(),
   11931          600 :                     &expected_result_at_gc_horizon[idx]
   11932           12 :                 );
   11933          600 :                 assert_eq!(
   11934          600 :                     tline
   11935          600 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11936          600 :                         .await
   11937          600 :                         .unwrap(),
   11938          600 :                     &expected_result_at_lsn_20[idx]
   11939           12 :                 );
   11940          600 :                 assert_eq!(
   11941          600 :                     tline
   11942          600 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11943          600 :                         .await
   11944          600 :                         .unwrap(),
   11945          600 :                     &expected_result_at_lsn_10[idx]
   11946           12 :                 );
   11947           12 :             }
   11948          120 :         };
   11949           12 : 
   11950           12 :         verify_result().await;
   11951           12 : 
   11952           12 :         let cancel = CancellationToken::new();
   11953           12 : 
   11954           12 :         tline
   11955           12 :             .compact_with_gc(
   11956           12 :                 &cancel,
   11957           12 :                 CompactOptions {
   11958           12 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11959           12 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   11960           12 :                     ..Default::default()
   11961           12 :                 },
   11962           12 :                 &ctx,
   11963           12 :             )
   11964           12 :             .await
   11965           12 :             .unwrap();
   11966           12 :         verify_result().await;
   11967           12 : 
   11968           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11969           12 :         check_layer_map_key_eq(
   11970           12 :             all_layers,
   11971           12 :             vec![
   11972           12 :                 // The original image layer, not compacted
   11973           12 :                 PersistentLayerKey {
   11974           12 :                     key_range: get_key(0)..get_key(10),
   11975           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11976           12 :                     is_delta: false,
   11977           12 :                 },
   11978           12 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   11979           12 :                 // the layer 0x28-0x30 into one.
   11980           12 :                 PersistentLayerKey {
   11981           12 :                     key_range: get_key(1)..get_key(2),
   11982           12 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11983           12 :                     is_delta: true,
   11984           12 :                 },
   11985           12 :                 // Above the upper bound and untouched
   11986           12 :                 PersistentLayerKey {
   11987           12 :                     key_range: get_key(1)..get_key(2),
   11988           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11989           12 :                     is_delta: true,
   11990           12 :                 },
   11991           12 :                 // This layer is untouched
   11992           12 :                 PersistentLayerKey {
   11993           12 :                     key_range: get_key(8)..get_key(10),
   11994           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11995           12 :                     is_delta: true,
   11996           12 :                 },
   11997           12 :             ],
   11998           12 :         );
   11999           12 : 
   12000           12 :         tline
   12001           12 :             .compact_with_gc(
   12002           12 :                 &cancel,
   12003           12 :                 CompactOptions {
   12004           12 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12005           12 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12006           12 :                     ..Default::default()
   12007           12 :                 },
   12008           12 :                 &ctx,
   12009           12 :             )
   12010           12 :             .await
   12011           12 :             .unwrap();
   12012           12 :         verify_result().await;
   12013           12 : 
   12014           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12015           12 :         check_layer_map_key_eq(
   12016           12 :             all_layers,
   12017           12 :             vec![
   12018           12 :                 // The original image layer, not compacted
   12019           12 :                 PersistentLayerKey {
   12020           12 :                     key_range: get_key(0)..get_key(10),
   12021           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12022           12 :                     is_delta: false,
   12023           12 :                 },
   12024           12 :                 // Not in the compaction key range, uncompacted
   12025           12 :                 PersistentLayerKey {
   12026           12 :                     key_range: get_key(1)..get_key(2),
   12027           12 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12028           12 :                     is_delta: true,
   12029           12 :                 },
   12030           12 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12031           12 :                 PersistentLayerKey {
   12032           12 :                     key_range: get_key(1)..get_key(2),
   12033           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12034           12 :                     is_delta: true,
   12035           12 :                 },
   12036           12 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12037           12 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12038           12 :                 // becomes 0x50.
   12039           12 :                 PersistentLayerKey {
   12040           12 :                     key_range: get_key(8)..get_key(10),
   12041           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12042           12 :                     is_delta: true,
   12043           12 :                 },
   12044           12 :             ],
   12045           12 :         );
   12046           12 : 
   12047           12 :         // compact again
   12048           12 :         tline
   12049           12 :             .compact_with_gc(
   12050           12 :                 &cancel,
   12051           12 :                 CompactOptions {
   12052           12 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12053           12 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12054           12 :                     ..Default::default()
   12055           12 :                 },
   12056           12 :                 &ctx,
   12057           12 :             )
   12058           12 :             .await
   12059           12 :             .unwrap();
   12060           12 :         verify_result().await;
   12061           12 : 
   12062           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12063           12 :         check_layer_map_key_eq(
   12064           12 :             all_layers,
   12065           12 :             vec![
   12066           12 :                 // The original image layer, not compacted
   12067           12 :                 PersistentLayerKey {
   12068           12 :                     key_range: get_key(0)..get_key(10),
   12069           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12070           12 :                     is_delta: false,
   12071           12 :                 },
   12072           12 :                 // The range gets compacted
   12073           12 :                 PersistentLayerKey {
   12074           12 :                     key_range: get_key(1)..get_key(2),
   12075           12 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12076           12 :                     is_delta: true,
   12077           12 :                 },
   12078           12 :                 // Not touched during this iteration of compaction
   12079           12 :                 PersistentLayerKey {
   12080           12 :                     key_range: get_key(8)..get_key(10),
   12081           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12082           12 :                     is_delta: true,
   12083           12 :                 },
   12084           12 :             ],
   12085           12 :         );
   12086           12 : 
   12087           12 :         // final full compaction
   12088           12 :         tline
   12089           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12090           12 :             .await
   12091           12 :             .unwrap();
   12092           12 :         verify_result().await;
   12093           12 : 
   12094           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12095           12 :         check_layer_map_key_eq(
   12096           12 :             all_layers,
   12097           12 :             vec![
   12098           12 :                 // The compacted image layer (full key range)
   12099           12 :                 PersistentLayerKey {
   12100           12 :                     key_range: Key::MIN..Key::MAX,
   12101           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12102           12 :                     is_delta: false,
   12103           12 :                 },
   12104           12 :                 // All other data in the delta layer
   12105           12 :                 PersistentLayerKey {
   12106           12 :                     key_range: get_key(1)..get_key(10),
   12107           12 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12108           12 :                     is_delta: true,
   12109           12 :                 },
   12110           12 :             ],
   12111           12 :         );
   12112           12 : 
   12113           12 :         Ok(())
   12114           12 :     }
   12115              : 
   12116              :     #[cfg(feature = "testing")]
   12117              :     #[tokio::test]
   12118           12 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12119           12 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12120           12 :         let (tenant, ctx) = harness.load().await;
   12121           12 : 
   12122          156 :         fn get_key(id: u32) -> Key {
   12123          156 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12124          156 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12125          156 :             key.field6 = id;
   12126          156 :             key
   12127          156 :         }
   12128           12 : 
   12129           12 :         let img_layer = (0..10)
   12130          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12131           12 :             .collect_vec();
   12132           12 : 
   12133           12 :         let delta1 = vec![
   12134           12 :             (
   12135           12 :                 get_key(1),
   12136           12 :                 Lsn(0x20),
   12137           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12138           12 :             ),
   12139           12 :             (
   12140           12 :                 get_key(1),
   12141           12 :                 Lsn(0x24),
   12142           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12143           12 :             ),
   12144           12 :             (
   12145           12 :                 get_key(1),
   12146           12 :                 Lsn(0x28),
   12147           12 :                 // This record will fail to redo
   12148           12 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12149           12 :             ),
   12150           12 :         ];
   12151           12 : 
   12152           12 :         let tline = tenant
   12153           12 :             .create_test_timeline_with_layers(
   12154           12 :                 TIMELINE_ID,
   12155           12 :                 Lsn(0x10),
   12156           12 :                 DEFAULT_PG_VERSION,
   12157           12 :                 &ctx,
   12158           12 :                 vec![], // in-memory layers
   12159           12 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12160           12 :                     Lsn(0x20)..Lsn(0x30),
   12161           12 :                     delta1,
   12162           12 :                 )], // delta layers
   12163           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12164           12 :                 Lsn(0x50),
   12165           12 :             )
   12166           12 :             .await?;
   12167           12 :         {
   12168           12 :             tline
   12169           12 :                 .applied_gc_cutoff_lsn
   12170           12 :                 .lock_for_write()
   12171           12 :                 .store_and_unlock(Lsn(0x30))
   12172           12 :                 .wait()
   12173           12 :                 .await;
   12174           12 :             // Update GC info
   12175           12 :             let mut guard = tline.gc_info.write().unwrap();
   12176           12 :             *guard = GcInfo {
   12177           12 :                 retain_lsns: vec![],
   12178           12 :                 cutoffs: GcCutoffs {
   12179           12 :                     time: Lsn(0x30),
   12180           12 :                     space: Lsn(0x30),
   12181           12 :                 },
   12182           12 :                 leases: Default::default(),
   12183           12 :                 within_ancestor_pitr: false,
   12184           12 :             };
   12185           12 :         }
   12186           12 : 
   12187           12 :         let cancel = CancellationToken::new();
   12188           12 : 
   12189           12 :         // Compaction will fail, but should not fire any critical error.
   12190           12 :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12191           12 :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12192           12 :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12193           12 :         let res = tline
   12194           12 :             .compact_with_gc(
   12195           12 :                 &cancel,
   12196           12 :                 CompactOptions {
   12197           12 :                     compact_key_range: None,
   12198           12 :                     compact_lsn_range: None,
   12199           12 :                     ..Default::default()
   12200           12 :                 },
   12201           12 :                 &ctx,
   12202           12 :             )
   12203           12 :             .await;
   12204           12 :         assert!(res.is_err());
   12205           12 : 
   12206           12 :         Ok(())
   12207           12 :     }
   12208              : 
   12209              :     #[cfg(feature = "testing")]
   12210              :     #[tokio::test]
   12211           12 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12212           12 :         use pageserver_api::models::TimelineVisibilityState;
   12213           12 : 
   12214           12 :         use crate::tenant::size::gather_inputs;
   12215           12 : 
   12216           12 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12217           12 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12218           12 :             pitr_interval: Some(Duration::ZERO),
   12219           12 :             ..Default::default()
   12220           12 :         };
   12221           12 :         let harness = TenantHarness::create_custom(
   12222           12 :             "test_synthetic_size_calculation_with_invisible_branches",
   12223           12 :             tenant_conf,
   12224           12 :             TenantId::generate(),
   12225           12 :             ShardIdentity::unsharded(),
   12226           12 :             Generation::new(0xdeadbeef),
   12227           12 :         )
   12228           12 :         .await?;
   12229           12 :         let (tenant, ctx) = harness.load().await;
   12230           12 :         let main_tline = tenant
   12231           12 :             .create_test_timeline_with_layers(
   12232           12 :                 TIMELINE_ID,
   12233           12 :                 Lsn(0x10),
   12234           12 :                 DEFAULT_PG_VERSION,
   12235           12 :                 &ctx,
   12236           12 :                 vec![],
   12237           12 :                 vec![],
   12238           12 :                 vec![],
   12239           12 :                 Lsn(0x100),
   12240           12 :             )
   12241           12 :             .await?;
   12242           12 : 
   12243           12 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12244           12 :         tenant
   12245           12 :             .branch_timeline_test_with_layers(
   12246           12 :                 &main_tline,
   12247           12 :                 snapshot1,
   12248           12 :                 Some(Lsn(0x20)),
   12249           12 :                 &ctx,
   12250           12 :                 vec![],
   12251           12 :                 vec![],
   12252           12 :                 Lsn(0x50),
   12253           12 :             )
   12254           12 :             .await?;
   12255           12 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12256           12 :         tenant
   12257           12 :             .branch_timeline_test_with_layers(
   12258           12 :                 &main_tline,
   12259           12 :                 snapshot2,
   12260           12 :                 Some(Lsn(0x30)),
   12261           12 :                 &ctx,
   12262           12 :                 vec![],
   12263           12 :                 vec![],
   12264           12 :                 Lsn(0x50),
   12265           12 :             )
   12266           12 :             .await?;
   12267           12 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12268           12 :         tenant
   12269           12 :             .branch_timeline_test_with_layers(
   12270           12 :                 &main_tline,
   12271           12 :                 snapshot3,
   12272           12 :                 Some(Lsn(0x40)),
   12273           12 :                 &ctx,
   12274           12 :                 vec![],
   12275           12 :                 vec![],
   12276           12 :                 Lsn(0x50),
   12277           12 :             )
   12278           12 :             .await?;
   12279           12 :         let limit = Arc::new(Semaphore::new(1));
   12280           12 :         let max_retention_period = None;
   12281           12 :         let mut logical_size_cache = HashMap::new();
   12282           12 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12283           12 :         let cancel = CancellationToken::new();
   12284           12 : 
   12285           12 :         let inputs = gather_inputs(
   12286           12 :             &tenant,
   12287           12 :             &limit,
   12288           12 :             max_retention_period,
   12289           12 :             &mut logical_size_cache,
   12290           12 :             cause,
   12291           12 :             &cancel,
   12292           12 :             &ctx,
   12293           12 :         )
   12294           12 :         .instrument(info_span!(
   12295           12 :             "gather_inputs",
   12296           12 :             tenant_id = "unknown",
   12297           12 :             shard_id = "unknown",
   12298           12 :         ))
   12299           12 :         .await?;
   12300           12 :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12301           12 :         use LsnKind::*;
   12302           12 :         use tenant_size_model::Segment;
   12303           12 :         let ModelInputs { mut segments, .. } = inputs;
   12304          180 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12305           72 :         for segment in segments.iter_mut() {
   12306           72 :             segment.segment.parent = None; // We don't care about the parent for the test
   12307           72 :             segment.segment.size = None; // We don't care about the size for the test
   12308           72 :         }
   12309           12 :         assert_eq!(
   12310           12 :             segments,
   12311           12 :             [
   12312           12 :                 SegmentMeta {
   12313           12 :                     segment: Segment {
   12314           12 :                         parent: None,
   12315           12 :                         lsn: 0x10,
   12316           12 :                         size: None,
   12317           12 :                         needed: false,
   12318           12 :                     },
   12319           12 :                     timeline_id: TIMELINE_ID,
   12320           12 :                     kind: BranchStart,
   12321           12 :                 },
   12322           12 :                 SegmentMeta {
   12323           12 :                     segment: Segment {
   12324           12 :                         parent: None,
   12325           12 :                         lsn: 0x20,
   12326           12 :                         size: None,
   12327           12 :                         needed: false,
   12328           12 :                     },
   12329           12 :                     timeline_id: TIMELINE_ID,
   12330           12 :                     kind: BranchPoint,
   12331           12 :                 },
   12332           12 :                 SegmentMeta {
   12333           12 :                     segment: Segment {
   12334           12 :                         parent: None,
   12335           12 :                         lsn: 0x30,
   12336           12 :                         size: None,
   12337           12 :                         needed: false,
   12338           12 :                     },
   12339           12 :                     timeline_id: TIMELINE_ID,
   12340           12 :                     kind: BranchPoint,
   12341           12 :                 },
   12342           12 :                 SegmentMeta {
   12343           12 :                     segment: Segment {
   12344           12 :                         parent: None,
   12345           12 :                         lsn: 0x40,
   12346           12 :                         size: None,
   12347           12 :                         needed: false,
   12348           12 :                     },
   12349           12 :                     timeline_id: TIMELINE_ID,
   12350           12 :                     kind: BranchPoint,
   12351           12 :                 },
   12352           12 :                 SegmentMeta {
   12353           12 :                     segment: Segment {
   12354           12 :                         parent: None,
   12355           12 :                         lsn: 0x100,
   12356           12 :                         size: None,
   12357           12 :                         needed: false,
   12358           12 :                     },
   12359           12 :                     timeline_id: TIMELINE_ID,
   12360           12 :                     kind: GcCutOff,
   12361           12 :                 }, // we need to retain everything above the last branch point
   12362           12 :                 SegmentMeta {
   12363           12 :                     segment: Segment {
   12364           12 :                         parent: None,
   12365           12 :                         lsn: 0x100,
   12366           12 :                         size: None,
   12367           12 :                         needed: true,
   12368           12 :                     },
   12369           12 :                     timeline_id: TIMELINE_ID,
   12370           12 :                     kind: BranchEnd,
   12371           12 :                 },
   12372           12 :             ]
   12373           12 :         );
   12374           12 : 
   12375           12 :         main_tline
   12376           12 :             .remote_client
   12377           12 :             .schedule_index_upload_for_timeline_invisible_state(
   12378           12 :                 TimelineVisibilityState::Invisible,
   12379           12 :             )?;
   12380           12 :         main_tline.remote_client.wait_completion().await?;
   12381           12 :         let inputs = gather_inputs(
   12382           12 :             &tenant,
   12383           12 :             &limit,
   12384           12 :             max_retention_period,
   12385           12 :             &mut logical_size_cache,
   12386           12 :             cause,
   12387           12 :             &cancel,
   12388           12 :             &ctx,
   12389           12 :         )
   12390           12 :         .instrument(info_span!(
   12391           12 :             "gather_inputs",
   12392           12 :             tenant_id = "unknown",
   12393           12 :             shard_id = "unknown",
   12394           12 :         ))
   12395           12 :         .await?;
   12396           12 :         let ModelInputs { mut segments, .. } = inputs;
   12397          168 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12398           60 :         for segment in segments.iter_mut() {
   12399           60 :             segment.segment.parent = None; // We don't care about the parent for the test
   12400           60 :             segment.segment.size = None; // We don't care about the size for the test
   12401           60 :         }
   12402           12 :         assert_eq!(
   12403           12 :             segments,
   12404           12 :             [
   12405           12 :                 SegmentMeta {
   12406           12 :                     segment: Segment {
   12407           12 :                         parent: None,
   12408           12 :                         lsn: 0x10,
   12409           12 :                         size: None,
   12410           12 :                         needed: false,
   12411           12 :                     },
   12412           12 :                     timeline_id: TIMELINE_ID,
   12413           12 :                     kind: BranchStart,
   12414           12 :                 },
   12415           12 :                 SegmentMeta {
   12416           12 :                     segment: Segment {
   12417           12 :                         parent: None,
   12418           12 :                         lsn: 0x20,
   12419           12 :                         size: None,
   12420           12 :                         needed: false,
   12421           12 :                     },
   12422           12 :                     timeline_id: TIMELINE_ID,
   12423           12 :                     kind: BranchPoint,
   12424           12 :                 },
   12425           12 :                 SegmentMeta {
   12426           12 :                     segment: Segment {
   12427           12 :                         parent: None,
   12428           12 :                         lsn: 0x30,
   12429           12 :                         size: None,
   12430           12 :                         needed: false,
   12431           12 :                     },
   12432           12 :                     timeline_id: TIMELINE_ID,
   12433           12 :                     kind: BranchPoint,
   12434           12 :                 },
   12435           12 :                 SegmentMeta {
   12436           12 :                     segment: Segment {
   12437           12 :                         parent: None,
   12438           12 :                         lsn: 0x40,
   12439           12 :                         size: None,
   12440           12 :                         needed: false,
   12441           12 :                     },
   12442           12 :                     timeline_id: TIMELINE_ID,
   12443           12 :                     kind: BranchPoint,
   12444           12 :                 },
   12445           12 :                 SegmentMeta {
   12446           12 :                     segment: Segment {
   12447           12 :                         parent: None,
   12448           12 :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12449           12 :                         size: None,
   12450           12 :                         needed: true,
   12451           12 :                     },
   12452           12 :                     timeline_id: TIMELINE_ID,
   12453           12 :                     kind: BranchEnd,
   12454           12 :                 },
   12455           12 :             ]
   12456           12 :         );
   12457           12 :         Ok(())
   12458           12 :     }
   12459              : }
        

Generated by: LCOV version 2.1-beta