LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 1b0a6a0c05cee5a7de360813c8034804e105ce1c.info Lines: 76.3 % 8822 6734
Test Date: 2025-03-12 00:01:28 Functions: 59.8 % 453 271

            Line data    Source code
       1              : //! Timeline repository implementation that keeps old data in layer files, and
       2              : //! the recent changes in ephemeral files.
       3              : //!
       4              : //! See tenant/*_layer.rs files. The functions here are responsible for locating
       5              : //! the correct layer for the get/put call, walking back the timeline branching
       6              : //! history as needed.
       7              : //!
       8              : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
       9              : //! directory. See docs/pageserver-storage.md for how the files are managed.
      10              : //! In addition to the layer files, there is a metadata file in the same
      11              : //! directory that contains information about the timeline, in particular its
      12              : //! parent timeline, and the last LSN that has been written to disk.
      13              : //!
      14              : 
      15              : use std::collections::hash_map::Entry;
      16              : use std::collections::{BTreeMap, HashMap, HashSet};
      17              : use std::fmt::{Debug, Display};
      18              : use std::fs::File;
      19              : use std::future::Future;
      20              : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
      21              : use std::sync::{Arc, Mutex, Weak};
      22              : use std::time::{Duration, Instant, SystemTime};
      23              : use std::{fmt, fs};
      24              : 
      25              : use anyhow::{Context, bail};
      26              : use arc_swap::ArcSwap;
      27              : use camino::{Utf8Path, Utf8PathBuf};
      28              : use chrono::NaiveDateTime;
      29              : use enumset::EnumSet;
      30              : use futures::StreamExt;
      31              : use futures::stream::FuturesUnordered;
      32              : use itertools::Itertools as _;
      33              : use once_cell::sync::Lazy;
      34              : pub use pageserver_api::models::TenantState;
      35              : use pageserver_api::models::{self, RelSizeMigration};
      36              : use pageserver_api::models::{
      37              :     CompactInfoResponse, LsnLease, TimelineArchivalState, TimelineState, TopTenantShardItem,
      38              :     WalRedoManagerStatus,
      39              : };
      40              : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
      41              : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
      42              : use remote_timeline_client::index::GcCompactionState;
      43              : use remote_timeline_client::manifest::{
      44              :     LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
      45              : };
      46              : use remote_timeline_client::{
      47              :     FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
      48              : };
      49              : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
      50              : use storage_broker::BrokerClientChannel;
      51              : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
      52              : use timeline::offload::{OffloadError, offload_timeline};
      53              : use timeline::{
      54              :     CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
      55              : };
      56              : use tokio::io::BufReader;
      57              : use tokio::sync::{Notify, Semaphore, watch};
      58              : use tokio::task::JoinSet;
      59              : use tokio_util::sync::CancellationToken;
      60              : use tracing::*;
      61              : use upload_queue::NotInitialized;
      62              : use utils::circuit_breaker::CircuitBreaker;
      63              : use utils::crashsafe::path_with_suffix_extension;
      64              : use utils::sync::gate::{Gate, GateGuard};
      65              : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
      66              : use utils::try_rcu::ArcSwapExt;
      67              : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
      68              : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
      69              : 
      70              : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf, TenantConf};
      71              : use self::metadata::TimelineMetadata;
      72              : use self::mgr::{GetActiveTenantError, GetTenantError};
      73              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      74              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      75              : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
      76              : use self::timeline::{
      77              :     EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
      78              : };
      79              : use crate::config::PageServerConf;
      80              : use crate::context;
      81              : use crate::context::RequestContextBuilder;
      82              : use crate::context::{DownloadBehavior, RequestContext};
      83              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
      84              : use crate::l0_flush::L0FlushGlobalState;
      85              : use crate::metrics::{
      86              :     BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
      87              :     INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_STATE_METRIC,
      88              :     TENANT_SYNTHETIC_SIZE_METRIC, remove_tenant_metrics,
      89              : };
      90              : use crate::task_mgr::TaskKind;
      91              : use crate::tenant::config::{LocationMode, TenantConfOpt};
      92              : use crate::tenant::gc_result::GcResult;
      93              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
      94              : use crate::tenant::remote_timeline_client::{
      95              :     INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
      96              : };
      97              : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
      98              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
      99              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     100              : use crate::virtual_file::VirtualFile;
     101              : use crate::walingest::WalLagCooldown;
     102              : use crate::walredo::PostgresRedoManager;
     103              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
     104              : 
     105            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     106              : use utils::crashsafe;
     107              : use utils::generation::Generation;
     108              : use utils::id::TimelineId;
     109              : use utils::lsn::{Lsn, RecordLsn};
     110              : 
     111              : pub mod blob_io;
     112              : pub mod block_io;
     113              : pub mod vectored_blob_io;
     114              : 
     115              : pub mod disk_btree;
     116              : pub(crate) mod ephemeral_file;
     117              : pub mod layer_map;
     118              : 
     119              : pub mod metadata;
     120              : pub mod remote_timeline_client;
     121              : pub mod storage_layer;
     122              : 
     123              : pub mod checks;
     124              : pub mod config;
     125              : pub mod mgr;
     126              : pub mod secondary;
     127              : pub mod tasks;
     128              : pub mod upload_queue;
     129              : 
     130              : pub(crate) mod timeline;
     131              : 
     132              : pub mod size;
     133              : 
     134              : mod gc_block;
     135              : mod gc_result;
     136              : pub(crate) mod throttle;
     137              : 
     138              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     139              : 
     140              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     141              : // re-export for use in walreceiver
     142              : pub use crate::tenant::timeline::WalReceiverInfo;
     143              : 
     144              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     145              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     146              : 
     147              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     148              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     149              : 
     150              : /// References to shared objects that are passed into each tenant, such
     151              : /// as the shared remote storage client and process initialization state.
     152              : #[derive(Clone)]
     153              : pub struct TenantSharedResources {
     154              :     pub broker_client: storage_broker::BrokerClientChannel,
     155              :     pub remote_storage: GenericRemoteStorage,
     156              :     pub deletion_queue_client: DeletionQueueClient,
     157              :     pub l0_flush_global_state: L0FlushGlobalState,
     158              : }
     159              : 
     160              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     161              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     162              : /// in this struct.
     163              : #[derive(Clone)]
     164              : pub(super) struct AttachedTenantConf {
     165              :     tenant_conf: TenantConfOpt,
     166              :     location: AttachedLocationConfig,
     167              :     /// The deadline before which we are blocked from GC so that
     168              :     /// leases have a chance to be renewed.
     169              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     170              : }
     171              : 
     172              : impl AttachedTenantConf {
     173          452 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     174              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     175              :         //
     176              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     177              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     178              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     179          452 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     180          452 :             Some(
     181          452 :                 tokio::time::Instant::now()
     182          452 :                     + tenant_conf
     183          452 :                         .lsn_lease_length
     184          452 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     185          452 :             )
     186              :         } else {
     187              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     188              :             // because we don't do GC in these modes.
     189            0 :             None
     190              :         };
     191              : 
     192          452 :         Self {
     193          452 :             tenant_conf,
     194          452 :             location,
     195          452 :             lsn_lease_deadline,
     196          452 :         }
     197          452 :     }
     198              : 
     199          452 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     200          452 :         match &location_conf.mode {
     201          452 :             LocationMode::Attached(attach_conf) => {
     202          452 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     203              :             }
     204              :             LocationMode::Secondary(_) => {
     205            0 :                 anyhow::bail!(
     206            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     207            0 :                 )
     208              :             }
     209              :         }
     210          452 :     }
     211              : 
     212         1524 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     213         1524 :         self.lsn_lease_deadline
     214         1524 :             .map(|d| tokio::time::Instant::now() < d)
     215         1524 :             .unwrap_or(false)
     216         1524 :     }
     217              : }
     218              : struct TimelinePreload {
     219              :     timeline_id: TimelineId,
     220              :     client: RemoteTimelineClient,
     221              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     222              :     previous_heatmap: Option<PreviousHeatmap>,
     223              : }
     224              : 
     225              : pub(crate) struct TenantPreload {
     226              :     tenant_manifest: TenantManifest,
     227              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     228              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     229              : }
     230              : 
     231              : /// When we spawn a tenant, there is a special mode for tenant creation that
     232              : /// avoids trying to read anything from remote storage.
     233              : pub(crate) enum SpawnMode {
     234              :     /// Activate as soon as possible
     235              :     Eager,
     236              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     237              :     Lazy,
     238              : }
     239              : 
     240              : ///
     241              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     242              : ///
     243              : pub struct Tenant {
     244              :     // Global pageserver config parameters
     245              :     pub conf: &'static PageServerConf,
     246              : 
     247              :     /// The value creation timestamp, used to measure activation delay, see:
     248              :     /// <https://github.com/neondatabase/neon/issues/4025>
     249              :     constructed_at: Instant,
     250              : 
     251              :     state: watch::Sender<TenantState>,
     252              : 
     253              :     // Overridden tenant-specific config parameters.
     254              :     // We keep TenantConfOpt sturct here to preserve the information
     255              :     // about parameters that are not set.
     256              :     // This is necessary to allow global config updates.
     257              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     258              : 
     259              :     tenant_shard_id: TenantShardId,
     260              : 
     261              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     262              :     shard_identity: ShardIdentity,
     263              : 
     264              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     265              :     /// Does not change over the lifetime of the [`Tenant`] object.
     266              :     ///
     267              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     268              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     269              :     generation: Generation,
     270              : 
     271              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     272              : 
     273              :     /// During timeline creation, we first insert the TimelineId to the
     274              :     /// creating map, then `timelines`, then remove it from the creating map.
     275              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     276              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     277              : 
     278              :     /// Possibly offloaded and archived timelines
     279              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     280              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     281              : 
     282              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     283              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     284              :     /// each other (this could be optimized to coalesce writes if necessary).
     285              :     ///
     286              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     287              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     288              : 
     289              :     // This mutex prevents creation of new timelines during GC.
     290              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     291              :     // `timelines` mutex during all GC iteration
     292              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     293              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     294              :     // timeout...
     295              :     gc_cs: tokio::sync::Mutex<()>,
     296              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     297              : 
     298              :     // provides access to timeline data sitting in the remote storage
     299              :     pub(crate) remote_storage: GenericRemoteStorage,
     300              : 
     301              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     302              :     deletion_queue_client: DeletionQueueClient,
     303              : 
     304              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     305              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     306              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     307              : 
     308              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     309              : 
     310              :     /// Track repeated failures to compact, so that we can back off.
     311              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     312              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     313              : 
     314              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     315              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     316              : 
     317              :     /// Scheduled gc-compaction tasks.
     318              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     319              : 
     320              :     /// If the tenant is in Activating state, notify this to encourage it
     321              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     322              :     /// background warmup.
     323              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     324              : 
     325              :     /// Time it took for the tenant to activate. Zero if not active yet.
     326              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     327              : 
     328              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     329              :     // Timelines' cancellation token.
     330              :     pub(crate) cancel: CancellationToken,
     331              : 
     332              :     // Users of the Tenant such as the page service must take this Gate to avoid
     333              :     // trying to use a Tenant which is shutting down.
     334              :     pub(crate) gate: Gate,
     335              : 
     336              :     /// Throttle applied at the top of [`Timeline::get`].
     337              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     338              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     339              : 
     340              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     341              : 
     342              :     /// An ongoing timeline detach concurrency limiter.
     343              :     ///
     344              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     345              :     /// to have two running at the same time. A different one can be started if an earlier one
     346              :     /// has failed for whatever reason.
     347              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     348              : 
     349              :     /// `index_part.json` based gc blocking reason tracking.
     350              :     ///
     351              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     352              :     /// proceeding.
     353              :     pub(crate) gc_block: gc_block::GcBlock,
     354              : 
     355              :     l0_flush_global_state: L0FlushGlobalState,
     356              : }
     357              : impl std::fmt::Debug for Tenant {
     358            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     359            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     360            0 :     }
     361              : }
     362              : 
     363              : pub(crate) enum WalRedoManager {
     364              :     Prod(WalredoManagerId, PostgresRedoManager),
     365              :     #[cfg(test)]
     366              :     Test(harness::TestRedoManager),
     367              : }
     368              : 
     369              : #[derive(thiserror::Error, Debug)]
     370              : #[error("pageserver is shutting down")]
     371              : pub(crate) struct GlobalShutDown;
     372              : 
     373              : impl WalRedoManager {
     374            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     375            0 :         let id = WalredoManagerId::next();
     376            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     377            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     378            0 :         match &mut *guard {
     379            0 :             Some(map) => {
     380            0 :                 map.insert(id, Arc::downgrade(&arc));
     381            0 :                 Ok(arc)
     382              :             }
     383            0 :             None => Err(GlobalShutDown),
     384              :         }
     385            0 :     }
     386              : }
     387              : 
     388              : impl Drop for WalRedoManager {
     389           20 :     fn drop(&mut self) {
     390           20 :         match self {
     391            0 :             Self::Prod(id, _) => {
     392            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     393            0 :                 if let Some(map) = &mut *guard {
     394            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     395            0 :                 }
     396              :             }
     397              :             #[cfg(test)]
     398           20 :             Self::Test(_) => {
     399           20 :                 // Not applicable to test redo manager
     400           20 :             }
     401              :         }
     402           20 :     }
     403              : }
     404              : 
     405              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     406              : /// the walredo processes outside of the regular order.
     407              : ///
     408              : /// This is necessary to work around a systemd bug where it freezes if there are
     409              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     410              : #[allow(clippy::type_complexity)]
     411              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     412              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     413            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     414              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     415              : pub(crate) struct WalredoManagerId(u64);
     416              : impl WalredoManagerId {
     417            0 :     pub fn next() -> Self {
     418              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     419            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     420            0 :         if id == 0 {
     421            0 :             panic!(
     422            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     423            0 :             );
     424            0 :         }
     425            0 :         Self(id)
     426            0 :     }
     427              : }
     428              : 
     429              : #[cfg(test)]
     430              : impl From<harness::TestRedoManager> for WalRedoManager {
     431          452 :     fn from(mgr: harness::TestRedoManager) -> Self {
     432          452 :         Self::Test(mgr)
     433          452 :     }
     434              : }
     435              : 
     436              : impl WalRedoManager {
     437           12 :     pub(crate) async fn shutdown(&self) -> bool {
     438           12 :         match self {
     439            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     440              :             #[cfg(test)]
     441              :             Self::Test(_) => {
     442              :                 // Not applicable to test redo manager
     443           12 :                 true
     444              :             }
     445              :         }
     446           12 :     }
     447              : 
     448            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     449            0 :         match self {
     450            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     451            0 :             #[cfg(test)]
     452            0 :             Self::Test(_) => {
     453            0 :                 // Not applicable to test redo manager
     454            0 :             }
     455            0 :         }
     456            0 :     }
     457              : 
     458              :     /// # Cancel-Safety
     459              :     ///
     460              :     /// This method is cancellation-safe.
     461         1676 :     pub async fn request_redo(
     462         1676 :         &self,
     463         1676 :         key: pageserver_api::key::Key,
     464         1676 :         lsn: Lsn,
     465         1676 :         base_img: Option<(Lsn, bytes::Bytes)>,
     466         1676 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     467         1676 :         pg_version: u32,
     468         1676 :     ) -> Result<bytes::Bytes, walredo::Error> {
     469         1676 :         match self {
     470            0 :             Self::Prod(_, mgr) => {
     471            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     472            0 :                     .await
     473              :             }
     474              :             #[cfg(test)]
     475         1676 :             Self::Test(mgr) => {
     476         1676 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     477         1676 :                     .await
     478              :             }
     479              :         }
     480         1676 :     }
     481              : 
     482            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     483            0 :         match self {
     484            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     485            0 :             #[cfg(test)]
     486            0 :             WalRedoManager::Test(_) => None,
     487            0 :         }
     488            0 :     }
     489              : }
     490              : 
     491              : /// A very lightweight memory representation of an offloaded timeline.
     492              : ///
     493              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     494              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     495              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     496              : /// more offloaded timelines than we can manage ones that aren't.
     497              : pub struct OffloadedTimeline {
     498              :     pub tenant_shard_id: TenantShardId,
     499              :     pub timeline_id: TimelineId,
     500              :     pub ancestor_timeline_id: Option<TimelineId>,
     501              :     /// Whether to retain the branch lsn at the ancestor or not
     502              :     pub ancestor_retain_lsn: Option<Lsn>,
     503              : 
     504              :     /// When the timeline was archived.
     505              :     ///
     506              :     /// Present for future flattening deliberations.
     507              :     pub archived_at: NaiveDateTime,
     508              : 
     509              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     510              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     511              :     pub delete_progress: TimelineDeleteProgress,
     512              : 
     513              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     514              :     pub deleted_from_ancestor: AtomicBool,
     515              : }
     516              : 
     517              : impl OffloadedTimeline {
     518              :     /// Obtains an offloaded timeline from a given timeline object.
     519              :     ///
     520              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     521              :     /// the timeline is not in a stopped state.
     522              :     /// Panics if the timeline is not archived.
     523            4 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     524            4 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     525            4 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     526            4 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     527            4 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     528            4 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     529            4 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     530            4 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     531              :             } else {
     532            0 :                 (None, None)
     533              :             };
     534            4 :         let archived_at = timeline
     535            4 :             .remote_client
     536            4 :             .archived_at_stopped_queue()?
     537            4 :             .expect("must be called on an archived timeline");
     538            4 :         Ok(Self {
     539            4 :             tenant_shard_id: timeline.tenant_shard_id,
     540            4 :             timeline_id: timeline.timeline_id,
     541            4 :             ancestor_timeline_id,
     542            4 :             ancestor_retain_lsn,
     543            4 :             archived_at,
     544            4 : 
     545            4 :             delete_progress: timeline.delete_progress.clone(),
     546            4 :             deleted_from_ancestor: AtomicBool::new(false),
     547            4 :         })
     548            4 :     }
     549            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     550            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     551            0 :         // by the `initialize_gc_info` function.
     552            0 :         let OffloadedTimelineManifest {
     553            0 :             timeline_id,
     554            0 :             ancestor_timeline_id,
     555            0 :             ancestor_retain_lsn,
     556            0 :             archived_at,
     557            0 :         } = *manifest;
     558            0 :         Self {
     559            0 :             tenant_shard_id,
     560            0 :             timeline_id,
     561            0 :             ancestor_timeline_id,
     562            0 :             ancestor_retain_lsn,
     563            0 :             archived_at,
     564            0 :             delete_progress: TimelineDeleteProgress::default(),
     565            0 :             deleted_from_ancestor: AtomicBool::new(false),
     566            0 :         }
     567            0 :     }
     568            4 :     fn manifest(&self) -> OffloadedTimelineManifest {
     569            4 :         let Self {
     570            4 :             timeline_id,
     571            4 :             ancestor_timeline_id,
     572            4 :             ancestor_retain_lsn,
     573            4 :             archived_at,
     574            4 :             ..
     575            4 :         } = self;
     576            4 :         OffloadedTimelineManifest {
     577            4 :             timeline_id: *timeline_id,
     578            4 :             ancestor_timeline_id: *ancestor_timeline_id,
     579            4 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     580            4 :             archived_at: *archived_at,
     581            4 :         }
     582            4 :     }
     583              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     584            0 :     fn delete_from_ancestor_with_timelines(
     585            0 :         &self,
     586            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     587            0 :     ) {
     588            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     589            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     590              :         {
     591            0 :             if let Some((_, ancestor_timeline)) = timelines
     592            0 :                 .iter()
     593            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     594              :             {
     595            0 :                 let removal_happened = ancestor_timeline
     596            0 :                     .gc_info
     597            0 :                     .write()
     598            0 :                     .unwrap()
     599            0 :                     .remove_child_offloaded(self.timeline_id);
     600            0 :                 if !removal_happened {
     601            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     602            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     603            0 :                 }
     604            0 :             }
     605            0 :         }
     606            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     607            0 :     }
     608              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     609              :     ///
     610              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     611            4 :     fn defuse_for_tenant_drop(&self) {
     612            4 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     613            4 :     }
     614              : }
     615              : 
     616              : impl fmt::Debug for OffloadedTimeline {
     617            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     618            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     619            0 :     }
     620              : }
     621              : 
     622              : impl Drop for OffloadedTimeline {
     623            4 :     fn drop(&mut self) {
     624            4 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     625            0 :             tracing::warn!(
     626            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     627              :                 self.timeline_id
     628              :             );
     629            4 :         }
     630            4 :     }
     631              : }
     632              : 
     633              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     634              : pub enum MaybeOffloaded {
     635              :     Yes,
     636              :     No,
     637              : }
     638              : 
     639              : #[derive(Clone, Debug)]
     640              : pub enum TimelineOrOffloaded {
     641              :     Timeline(Arc<Timeline>),
     642              :     Offloaded(Arc<OffloadedTimeline>),
     643              : }
     644              : 
     645              : impl TimelineOrOffloaded {
     646            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     647            0 :         match self {
     648            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     649            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     650              :             }
     651            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     652            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     653              :             }
     654              :         }
     655            0 :     }
     656            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     657            0 :         self.arc_ref().tenant_shard_id()
     658            0 :     }
     659            0 :     pub fn timeline_id(&self) -> TimelineId {
     660            0 :         self.arc_ref().timeline_id()
     661            0 :     }
     662            4 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     663            4 :         match self {
     664            4 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     665            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     666              :         }
     667            4 :     }
     668            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     669            0 :         match self {
     670            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     671            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     672              :         }
     673            0 :     }
     674              : }
     675              : 
     676              : pub enum TimelineOrOffloadedArcRef<'a> {
     677              :     Timeline(&'a Arc<Timeline>),
     678              :     Offloaded(&'a Arc<OffloadedTimeline>),
     679              : }
     680              : 
     681              : impl TimelineOrOffloadedArcRef<'_> {
     682            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     683            0 :         match self {
     684            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     685            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     686              :         }
     687            0 :     }
     688            0 :     pub fn timeline_id(&self) -> TimelineId {
     689            0 :         match self {
     690            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     691            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     692              :         }
     693            0 :     }
     694              : }
     695              : 
     696              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     697            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     698            0 :         Self::Timeline(timeline)
     699            0 :     }
     700              : }
     701              : 
     702              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     703            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     704            0 :         Self::Offloaded(timeline)
     705            0 :     }
     706              : }
     707              : 
     708              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     709              : pub enum GetTimelineError {
     710              :     #[error("Timeline is shutting down")]
     711              :     ShuttingDown,
     712              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     713              :     NotActive {
     714              :         tenant_id: TenantShardId,
     715              :         timeline_id: TimelineId,
     716              :         state: TimelineState,
     717              :     },
     718              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     719              :     NotFound {
     720              :         tenant_id: TenantShardId,
     721              :         timeline_id: TimelineId,
     722              :     },
     723              : }
     724              : 
     725              : #[derive(Debug, thiserror::Error)]
     726              : pub enum LoadLocalTimelineError {
     727              :     #[error("FailedToLoad")]
     728              :     Load(#[source] anyhow::Error),
     729              :     #[error("FailedToResumeDeletion")]
     730              :     ResumeDeletion(#[source] anyhow::Error),
     731              : }
     732              : 
     733              : #[derive(thiserror::Error)]
     734              : pub enum DeleteTimelineError {
     735              :     #[error("NotFound")]
     736              :     NotFound,
     737              : 
     738              :     #[error("HasChildren")]
     739              :     HasChildren(Vec<TimelineId>),
     740              : 
     741              :     #[error("Timeline deletion is already in progress")]
     742              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     743              : 
     744              :     #[error("Cancelled")]
     745              :     Cancelled,
     746              : 
     747              :     #[error(transparent)]
     748              :     Other(#[from] anyhow::Error),
     749              : }
     750              : 
     751              : impl Debug for DeleteTimelineError {
     752            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     753            0 :         match self {
     754            0 :             Self::NotFound => write!(f, "NotFound"),
     755            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     756            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     757            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     758            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     759              :         }
     760            0 :     }
     761              : }
     762              : 
     763              : #[derive(thiserror::Error)]
     764              : pub enum TimelineArchivalError {
     765              :     #[error("NotFound")]
     766              :     NotFound,
     767              : 
     768              :     #[error("Timeout")]
     769              :     Timeout,
     770              : 
     771              :     #[error("Cancelled")]
     772              :     Cancelled,
     773              : 
     774              :     #[error("ancestor is archived: {}", .0)]
     775              :     HasArchivedParent(TimelineId),
     776              : 
     777              :     #[error("HasUnarchivedChildren")]
     778              :     HasUnarchivedChildren(Vec<TimelineId>),
     779              : 
     780              :     #[error("Timeline archival is already in progress")]
     781              :     AlreadyInProgress,
     782              : 
     783              :     #[error(transparent)]
     784              :     Other(anyhow::Error),
     785              : }
     786              : 
     787              : #[derive(thiserror::Error, Debug)]
     788              : pub(crate) enum TenantManifestError {
     789              :     #[error("Remote storage error: {0}")]
     790              :     RemoteStorage(anyhow::Error),
     791              : 
     792              :     #[error("Cancelled")]
     793              :     Cancelled,
     794              : }
     795              : 
     796              : impl From<TenantManifestError> for TimelineArchivalError {
     797            0 :     fn from(e: TenantManifestError) -> Self {
     798            0 :         match e {
     799            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     800            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     801              :         }
     802            0 :     }
     803              : }
     804              : 
     805              : impl Debug for TimelineArchivalError {
     806            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     807            0 :         match self {
     808            0 :             Self::NotFound => write!(f, "NotFound"),
     809            0 :             Self::Timeout => write!(f, "Timeout"),
     810            0 :             Self::Cancelled => write!(f, "Cancelled"),
     811            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     812            0 :             Self::HasUnarchivedChildren(c) => {
     813            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     814              :             }
     815            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     816            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     817              :         }
     818            0 :     }
     819              : }
     820              : 
     821              : pub enum SetStoppingError {
     822              :     AlreadyStopping(completion::Barrier),
     823              :     Broken,
     824              : }
     825              : 
     826              : impl Debug for SetStoppingError {
     827            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     828            0 :         match self {
     829            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     830            0 :             Self::Broken => write!(f, "Broken"),
     831              :         }
     832            0 :     }
     833              : }
     834              : 
     835              : /// Arguments to [`Tenant::create_timeline`].
     836              : ///
     837              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     838              : /// is `None`, the result of the timeline create call is not deterministic.
     839              : ///
     840              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     841              : #[derive(Debug)]
     842              : pub(crate) enum CreateTimelineParams {
     843              :     Bootstrap(CreateTimelineParamsBootstrap),
     844              :     Branch(CreateTimelineParamsBranch),
     845              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     846              : }
     847              : 
     848              : #[derive(Debug)]
     849              : pub(crate) struct CreateTimelineParamsBootstrap {
     850              :     pub(crate) new_timeline_id: TimelineId,
     851              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     852              :     pub(crate) pg_version: u32,
     853              : }
     854              : 
     855              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     856              : #[derive(Debug)]
     857              : pub(crate) struct CreateTimelineParamsBranch {
     858              :     pub(crate) new_timeline_id: TimelineId,
     859              :     pub(crate) ancestor_timeline_id: TimelineId,
     860              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     861              : }
     862              : 
     863              : #[derive(Debug)]
     864              : pub(crate) struct CreateTimelineParamsImportPgdata {
     865              :     pub(crate) new_timeline_id: TimelineId,
     866              :     pub(crate) location: import_pgdata::index_part_format::Location,
     867              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     868              : }
     869              : 
     870              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     871              : ///
     872              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     873              : ///
     874              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     875              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     876              : ///
     877              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     878              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     879              : ///
     880              : /// Notes:
     881              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     882              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     883              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     884              : ///
     885              : #[derive(Debug, Clone, PartialEq, Eq)]
     886              : pub(crate) enum CreateTimelineIdempotency {
     887              :     /// NB: special treatment, see comment in [`Self`].
     888              :     FailWithConflict,
     889              :     Bootstrap {
     890              :         pg_version: u32,
     891              :     },
     892              :     /// NB: branches always have the same `pg_version` as their ancestor.
     893              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     894              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     895              :     /// determining the child branch pg_version.
     896              :     Branch {
     897              :         ancestor_timeline_id: TimelineId,
     898              :         ancestor_start_lsn: Lsn,
     899              :     },
     900              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     901              : }
     902              : 
     903              : #[derive(Debug, Clone, PartialEq, Eq)]
     904              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     905              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     906              : }
     907              : 
     908              : /// What is returned by [`Tenant::start_creating_timeline`].
     909              : #[must_use]
     910              : enum StartCreatingTimelineResult {
     911              :     CreateGuard(TimelineCreateGuard),
     912              :     Idempotent(Arc<Timeline>),
     913              : }
     914              : 
     915              : enum TimelineInitAndSyncResult {
     916              :     ReadyToActivate(Arc<Timeline>),
     917              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     918              : }
     919              : 
     920              : impl TimelineInitAndSyncResult {
     921            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     922            0 :         match self {
     923            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     924            0 :             _ => None,
     925              :         }
     926            0 :     }
     927              : }
     928              : 
     929              : #[must_use]
     930              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     931              :     timeline: Arc<Timeline>,
     932              :     import_pgdata: import_pgdata::index_part_format::Root,
     933              :     guard: TimelineCreateGuard,
     934              : }
     935              : 
     936              : /// What is returned by [`Tenant::create_timeline`].
     937              : enum CreateTimelineResult {
     938              :     Created(Arc<Timeline>),
     939              :     Idempotent(Arc<Timeline>),
     940              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     941              :     /// we return this result, nor will this concrete object ever be added there.
     942              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     943              :     ImportSpawned(Arc<Timeline>),
     944              : }
     945              : 
     946              : impl CreateTimelineResult {
     947            0 :     fn discriminant(&self) -> &'static str {
     948            0 :         match self {
     949            0 :             Self::Created(_) => "Created",
     950            0 :             Self::Idempotent(_) => "Idempotent",
     951            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     952              :         }
     953            0 :     }
     954            0 :     fn timeline(&self) -> &Arc<Timeline> {
     955            0 :         match self {
     956            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     957            0 :         }
     958            0 :     }
     959              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     960              :     #[cfg(test)]
     961          460 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     962          460 :         match self {
     963          460 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     964          460 :         }
     965          460 :     }
     966              : }
     967              : 
     968              : #[derive(thiserror::Error, Debug)]
     969              : pub enum CreateTimelineError {
     970              :     #[error("creation of timeline with the given ID is in progress")]
     971              :     AlreadyCreating,
     972              :     #[error("timeline already exists with different parameters")]
     973              :     Conflict,
     974              :     #[error(transparent)]
     975              :     AncestorLsn(anyhow::Error),
     976              :     #[error("ancestor timeline is not active")]
     977              :     AncestorNotActive,
     978              :     #[error("ancestor timeline is archived")]
     979              :     AncestorArchived,
     980              :     #[error("tenant shutting down")]
     981              :     ShuttingDown,
     982              :     #[error(transparent)]
     983              :     Other(#[from] anyhow::Error),
     984              : }
     985              : 
     986              : #[derive(thiserror::Error, Debug)]
     987              : pub enum InitdbError {
     988              :     #[error("Operation was cancelled")]
     989              :     Cancelled,
     990              :     #[error(transparent)]
     991              :     Other(anyhow::Error),
     992              :     #[error(transparent)]
     993              :     Inner(postgres_initdb::Error),
     994              : }
     995              : 
     996              : enum CreateTimelineCause {
     997              :     Load,
     998              :     Delete,
     999              : }
    1000              : 
    1001              : enum LoadTimelineCause {
    1002              :     Attach,
    1003              :     Unoffload,
    1004              :     ImportPgdata {
    1005              :         create_guard: TimelineCreateGuard,
    1006              :         activate: ActivateTimelineArgs,
    1007              :     },
    1008              : }
    1009              : 
    1010              : #[derive(thiserror::Error, Debug)]
    1011              : pub(crate) enum GcError {
    1012              :     // The tenant is shutting down
    1013              :     #[error("tenant shutting down")]
    1014              :     TenantCancelled,
    1015              : 
    1016              :     // The tenant is shutting down
    1017              :     #[error("timeline shutting down")]
    1018              :     TimelineCancelled,
    1019              : 
    1020              :     // The tenant is in a state inelegible to run GC
    1021              :     #[error("not active")]
    1022              :     NotActive,
    1023              : 
    1024              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1025              :     #[error("not active")]
    1026              :     BadLsn { why: String },
    1027              : 
    1028              :     // A remote storage error while scheduling updates after compaction
    1029              :     #[error(transparent)]
    1030              :     Remote(anyhow::Error),
    1031              : 
    1032              :     // An error reading while calculating GC cutoffs
    1033              :     #[error(transparent)]
    1034              :     GcCutoffs(PageReconstructError),
    1035              : 
    1036              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1037              :     #[error("timeline not found")]
    1038              :     TimelineNotFound,
    1039              : }
    1040              : 
    1041              : impl From<PageReconstructError> for GcError {
    1042            0 :     fn from(value: PageReconstructError) -> Self {
    1043            0 :         match value {
    1044            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1045            0 :             other => Self::GcCutoffs(other),
    1046              :         }
    1047            0 :     }
    1048              : }
    1049              : 
    1050              : impl From<NotInitialized> for GcError {
    1051            0 :     fn from(value: NotInitialized) -> Self {
    1052            0 :         match value {
    1053            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1054            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1055              :         }
    1056            0 :     }
    1057              : }
    1058              : 
    1059              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1060            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1061            0 :         GcError::TimelineCancelled
    1062            0 :     }
    1063              : }
    1064              : 
    1065              : #[derive(thiserror::Error, Debug)]
    1066              : pub(crate) enum LoadConfigError {
    1067              :     #[error("TOML deserialization error: '{0}'")]
    1068              :     DeserializeToml(#[from] toml_edit::de::Error),
    1069              : 
    1070              :     #[error("Config not found at {0}")]
    1071              :     NotFound(Utf8PathBuf),
    1072              : }
    1073              : 
    1074              : impl Tenant {
    1075              :     /// Yet another helper for timeline initialization.
    1076              :     ///
    1077              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1078              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1079              :     /// - Downloads remote index file and adds remote files to the layer map
    1080              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1081              :     ///
    1082              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1083              :     /// it is marked as Active.
    1084              :     #[allow(clippy::too_many_arguments)]
    1085           12 :     async fn timeline_init_and_sync(
    1086           12 :         self: &Arc<Self>,
    1087           12 :         timeline_id: TimelineId,
    1088           12 :         resources: TimelineResources,
    1089           12 :         mut index_part: IndexPart,
    1090           12 :         metadata: TimelineMetadata,
    1091           12 :         previous_heatmap: Option<PreviousHeatmap>,
    1092           12 :         ancestor: Option<Arc<Timeline>>,
    1093           12 :         cause: LoadTimelineCause,
    1094           12 :         ctx: &RequestContext,
    1095           12 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1096           12 :         let tenant_id = self.tenant_shard_id;
    1097           12 : 
    1098           12 :         let import_pgdata = index_part.import_pgdata.take();
    1099           12 :         let idempotency = match &import_pgdata {
    1100            0 :             Some(import_pgdata) => {
    1101            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1102            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1103            0 :                 })
    1104              :             }
    1105              :             None => {
    1106           12 :                 if metadata.ancestor_timeline().is_none() {
    1107            8 :                     CreateTimelineIdempotency::Bootstrap {
    1108            8 :                         pg_version: metadata.pg_version(),
    1109            8 :                     }
    1110              :                 } else {
    1111            4 :                     CreateTimelineIdempotency::Branch {
    1112            4 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1113            4 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1114            4 :                     }
    1115              :                 }
    1116              :             }
    1117              :         };
    1118              : 
    1119           12 :         let (timeline, timeline_ctx) = self.create_timeline_struct(
    1120           12 :             timeline_id,
    1121           12 :             &metadata,
    1122           12 :             previous_heatmap,
    1123           12 :             ancestor.clone(),
    1124           12 :             resources,
    1125           12 :             CreateTimelineCause::Load,
    1126           12 :             idempotency.clone(),
    1127           12 :             index_part.gc_compaction.clone(),
    1128           12 :             index_part.rel_size_migration.clone(),
    1129           12 :             ctx,
    1130           12 :         )?;
    1131           12 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1132           12 :         anyhow::ensure!(
    1133           12 :             disk_consistent_lsn.is_valid(),
    1134            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1135              :         );
    1136           12 :         assert_eq!(
    1137           12 :             disk_consistent_lsn,
    1138           12 :             metadata.disk_consistent_lsn(),
    1139            0 :             "these are used interchangeably"
    1140              :         );
    1141              : 
    1142           12 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1143              : 
    1144           12 :         timeline
    1145           12 :             .load_layer_map(disk_consistent_lsn, index_part)
    1146           12 :             .await
    1147           12 :             .with_context(|| {
    1148            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1149           12 :             })?;
    1150              : 
    1151              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1152              :         // to the archival operation. To allow warming this timeline up, generate
    1153              :         // a previous heatmap which contains all visible layers in the layer map.
    1154              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1155              :         // for the timeline.
    1156           12 :         if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
    1157            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1158            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1159            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1160              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1161              :                 // If the current branch point greater than the previous one use the the heatmap
    1162              :                 // we just generated - it should include more layers.
    1163            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1164            0 :                     tline
    1165            0 :                         .previous_heatmap
    1166            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1167            0 :                 } else {
    1168            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1169              :                 }
    1170              : 
    1171            0 :                 match tline.ancestor_timeline() {
    1172            0 :                     Some(ancestor) => {
    1173            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1174              :                             // Ancestor timeline is shutting down.
    1175            0 :                             break;
    1176            0 :                         }
    1177            0 : 
    1178            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1179              :                     }
    1180            0 :                     None => {
    1181            0 :                         tline_ending_at = None;
    1182            0 :                     }
    1183              :                 }
    1184              :             }
    1185           12 :         }
    1186              : 
    1187            0 :         match import_pgdata {
    1188            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1189            0 :                 match cause {
    1190            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1191              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1192            0 :                         unreachable!(
    1193            0 :                             "ImportPgdata should not be reloading timeline import is done and persisted as such in s3"
    1194            0 :                         )
    1195              :                     }
    1196              :                 }
    1197            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1198            0 :                 if !guard.insert(timeline_id) {
    1199              :                     // We should never try and load the same timeline twice during startup
    1200            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1201            0 :                 }
    1202            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1203            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1204            0 :                     owning_tenant: self.clone(),
    1205            0 :                     timeline_id,
    1206            0 :                     idempotency,
    1207            0 :                     // The users of this specific return value don't need the timline_path in there.
    1208            0 :                     timeline_path: timeline
    1209            0 :                         .conf
    1210            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1211            0 :                 };
    1212            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1213            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1214            0 :                         timeline,
    1215            0 :                         import_pgdata,
    1216            0 :                         guard: timeline_create_guard,
    1217            0 :                     },
    1218            0 :                 ))
    1219              :             }
    1220              :             Some(_) | None => {
    1221              :                 {
    1222           12 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1223           12 :                     match timelines_accessor.entry(timeline_id) {
    1224              :                         // We should never try and load the same timeline twice during startup
    1225              :                         Entry::Occupied(_) => {
    1226            0 :                             unreachable!(
    1227            0 :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1228            0 :                             );
    1229              :                         }
    1230           12 :                         Entry::Vacant(v) => {
    1231           12 :                             v.insert(Arc::clone(&timeline));
    1232           12 :                             timeline.maybe_spawn_flush_loop();
    1233           12 :                         }
    1234              :                     }
    1235              :                 }
    1236              : 
    1237              :                 // Sanity check: a timeline should have some content.
    1238           12 :                 anyhow::ensure!(
    1239           12 :                     ancestor.is_some()
    1240            8 :                         || timeline
    1241            8 :                             .layers
    1242            8 :                             .read()
    1243            8 :                             .await
    1244            8 :                             .layer_map()
    1245            8 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1246            8 :                             .iter_historic_layers()
    1247            8 :                             .next()
    1248            8 :                             .is_some(),
    1249            0 :                     "Timeline has no ancestor and no layer files"
    1250              :                 );
    1251              : 
    1252           12 :                 match cause {
    1253           12 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1254              :                     LoadTimelineCause::ImportPgdata {
    1255            0 :                         create_guard,
    1256            0 :                         activate,
    1257            0 :                     } => {
    1258            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1259            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1260            0 :                         match activate {
    1261            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1262            0 :                                 info!("activating timeline after reload from pgdata import task");
    1263            0 :                                 timeline.activate(self.clone(), broker_client, None, &timeline_ctx);
    1264              :                             }
    1265            0 :                             ActivateTimelineArgs::No => (),
    1266              :                         }
    1267            0 :                         drop(create_guard);
    1268              :                     }
    1269              :                 }
    1270              : 
    1271           12 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1272              :             }
    1273              :         }
    1274           12 :     }
    1275              : 
    1276              :     /// Attach a tenant that's available in cloud storage.
    1277              :     ///
    1278              :     /// This returns quickly, after just creating the in-memory object
    1279              :     /// Tenant struct and launching a background task to download
    1280              :     /// the remote index files.  On return, the tenant is most likely still in
    1281              :     /// Attaching state, and it will become Active once the background task
    1282              :     /// finishes. You can use wait_until_active() to wait for the task to
    1283              :     /// complete.
    1284              :     ///
    1285              :     #[allow(clippy::too_many_arguments)]
    1286            0 :     pub(crate) fn spawn(
    1287            0 :         conf: &'static PageServerConf,
    1288            0 :         tenant_shard_id: TenantShardId,
    1289            0 :         resources: TenantSharedResources,
    1290            0 :         attached_conf: AttachedTenantConf,
    1291            0 :         shard_identity: ShardIdentity,
    1292            0 :         init_order: Option<InitializationOrder>,
    1293            0 :         mode: SpawnMode,
    1294            0 :         ctx: &RequestContext,
    1295            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1296            0 :         let wal_redo_manager =
    1297            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1298              : 
    1299              :         let TenantSharedResources {
    1300            0 :             broker_client,
    1301            0 :             remote_storage,
    1302            0 :             deletion_queue_client,
    1303            0 :             l0_flush_global_state,
    1304            0 :         } = resources;
    1305            0 : 
    1306            0 :         let attach_mode = attached_conf.location.attach_mode;
    1307            0 :         let generation = attached_conf.location.generation;
    1308            0 : 
    1309            0 :         let tenant = Arc::new(Tenant::new(
    1310            0 :             TenantState::Attaching,
    1311            0 :             conf,
    1312            0 :             attached_conf,
    1313            0 :             shard_identity,
    1314            0 :             Some(wal_redo_manager),
    1315            0 :             tenant_shard_id,
    1316            0 :             remote_storage.clone(),
    1317            0 :             deletion_queue_client,
    1318            0 :             l0_flush_global_state,
    1319            0 :         ));
    1320            0 : 
    1321            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1322            0 :         // we shut down while attaching.
    1323            0 :         let attach_gate_guard = tenant
    1324            0 :             .gate
    1325            0 :             .enter()
    1326            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1327            0 : 
    1328            0 :         // Do all the hard work in the background
    1329            0 :         let tenant_clone = Arc::clone(&tenant);
    1330            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1331            0 :         task_mgr::spawn(
    1332            0 :             &tokio::runtime::Handle::current(),
    1333            0 :             TaskKind::Attach,
    1334            0 :             tenant_shard_id,
    1335            0 :             None,
    1336            0 :             "attach tenant",
    1337            0 :             async move {
    1338            0 : 
    1339            0 :                 info!(
    1340              :                     ?attach_mode,
    1341            0 :                     "Attaching tenant"
    1342              :                 );
    1343              : 
    1344            0 :                 let _gate_guard = attach_gate_guard;
    1345            0 : 
    1346            0 :                 // Is this tenant being spawned as part of process startup?
    1347            0 :                 let starting_up = init_order.is_some();
    1348            0 :                 scopeguard::defer! {
    1349            0 :                     if starting_up {
    1350            0 :                         TENANT.startup_complete.inc();
    1351            0 :                     }
    1352            0 :                 }
    1353              : 
    1354              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1355              :                 enum BrokenVerbosity {
    1356              :                     Error,
    1357              :                     Info
    1358              :                 }
    1359            0 :                 let make_broken =
    1360            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1361            0 :                         match verbosity {
    1362              :                             BrokenVerbosity::Info => {
    1363            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1364              :                             },
    1365              :                             BrokenVerbosity::Error => {
    1366            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1367              :                             }
    1368              :                         }
    1369            0 :                         t.state.send_modify(|state| {
    1370            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1371            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1372            0 :                             assert!(
    1373            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1374            0 :                                 "the attach task owns the tenant state until activation is complete"
    1375              :                             );
    1376              : 
    1377            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1378            0 :                         });
    1379            0 :                     };
    1380              : 
    1381              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1382            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1383            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1384            0 :                     return Ok(());
    1385            0 :                 }
    1386            0 : 
    1387            0 :                 let mut init_order = init_order;
    1388            0 :                 // take the completion because initial tenant loading will complete when all of
    1389            0 :                 // these tasks complete.
    1390            0 :                 let _completion = init_order
    1391            0 :                     .as_mut()
    1392            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1393            0 :                 let remote_load_completion = init_order
    1394            0 :                     .as_mut()
    1395            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1396              : 
    1397              :                 enum AttachType<'a> {
    1398              :                     /// We are attaching this tenant lazily in the background.
    1399              :                     Warmup {
    1400              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1401              :                         during_startup: bool
    1402              :                     },
    1403              :                     /// We are attaching this tenant as soon as we can, because for example an
    1404              :                     /// endpoint tried to access it.
    1405              :                     OnDemand,
    1406              :                     /// During normal operations after startup, we are attaching a tenant, and
    1407              :                     /// eager attach was requested.
    1408              :                     Normal,
    1409              :                 }
    1410              : 
    1411            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1412              :                     // Before doing any I/O, wait for at least one of:
    1413              :                     // - A client attempting to access to this tenant (on-demand loading)
    1414              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1415              : 
    1416            0 :                     tokio::select!(
    1417            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1418            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1419            0 :                             tracing::info!("Activating tenant (on-demand)");
    1420            0 :                             AttachType::OnDemand
    1421              :                         },
    1422            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1423            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1424            0 :                             tracing::info!("Activating tenant (warmup)");
    1425            0 :                             AttachType::Warmup {
    1426            0 :                                 _permit,
    1427            0 :                                 during_startup: init_order.is_some()
    1428            0 :                             }
    1429              :                         }
    1430            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1431              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1432              :                             // stayed in Activating for such a long time that shutdown found it in
    1433              :                             // that state.
    1434            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1435              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1436              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1437              :                             // just shutting down), but ensures progress.
    1438            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1439            0 :                             return Ok(());
    1440              :                         },
    1441              :                     )
    1442              :                 } else {
    1443              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1444              :                     // concurrent_tenant_warmup queue
    1445            0 :                     AttachType::Normal
    1446              :                 };
    1447              : 
    1448            0 :                 let preload = match &mode {
    1449              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1450            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1451            0 :                         let res = tenant_clone
    1452            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1453            0 :                             .await;
    1454            0 :                         match res {
    1455            0 :                             Ok(p) => Some(p),
    1456            0 :                             Err(e) => {
    1457            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1458            0 :                                 return Ok(());
    1459              :                             }
    1460              :                         }
    1461              :                     }
    1462              : 
    1463              :                 };
    1464              : 
    1465              :                 // Remote preload is complete.
    1466            0 :                 drop(remote_load_completion);
    1467            0 : 
    1468            0 : 
    1469            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1470            0 :                 let attach_start = std::time::Instant::now();
    1471            0 :                 let attached = {
    1472            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1473            0 :                     tenant_clone.attach(preload, &ctx).await
    1474              :                 };
    1475            0 :                 let attach_duration = attach_start.elapsed();
    1476            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1477            0 : 
    1478            0 :                 match attached {
    1479              :                     Ok(()) => {
    1480            0 :                         info!("attach finished, activating");
    1481            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1482              :                     }
    1483            0 :                     Err(e) => {
    1484            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1485            0 :                     }
    1486              :                 }
    1487              : 
    1488              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1489              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1490              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1491              :                 //
    1492              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1493              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1494              :                 // then warmup will wait for that before proceeding to the next tenant.
    1495            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1496            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1497            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1498            0 :                     while futs.next().await.is_some() {}
    1499            0 :                     tracing::info!("Warm-up complete");
    1500            0 :                 }
    1501              : 
    1502            0 :                 Ok(())
    1503            0 :             }
    1504            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1505              :         );
    1506            0 :         Ok(tenant)
    1507            0 :     }
    1508              : 
    1509              :     #[instrument(skip_all)]
    1510              :     pub(crate) async fn preload(
    1511              :         self: &Arc<Self>,
    1512              :         remote_storage: &GenericRemoteStorage,
    1513              :         cancel: CancellationToken,
    1514              :     ) -> anyhow::Result<TenantPreload> {
    1515              :         span::debug_assert_current_span_has_tenant_id();
    1516              :         // Get list of remote timelines
    1517              :         // download index files for every tenant timeline
    1518              :         info!("listing remote timelines");
    1519              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1520              :             remote_storage,
    1521              :             self.tenant_shard_id,
    1522              :             cancel.clone(),
    1523              :         )
    1524              :         .await?;
    1525              :         let (offloaded_add, tenant_manifest) =
    1526              :             match remote_timeline_client::download_tenant_manifest(
    1527              :                 remote_storage,
    1528              :                 &self.tenant_shard_id,
    1529              :                 self.generation,
    1530              :                 &cancel,
    1531              :             )
    1532              :             .await
    1533              :             {
    1534              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1535              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1536              :                     tenant_manifest,
    1537              :                 ),
    1538              :                 Err(DownloadError::NotFound) => {
    1539              :                     ("no manifest".to_string(), TenantManifest::empty())
    1540              :                 }
    1541              :                 Err(e) => Err(e)?,
    1542              :             };
    1543              : 
    1544              :         info!(
    1545              :             "found {} timelines, and {offloaded_add}",
    1546              :             remote_timeline_ids.len()
    1547              :         );
    1548              : 
    1549              :         for k in other_keys {
    1550              :             warn!("Unexpected non timeline key {k}");
    1551              :         }
    1552              : 
    1553              :         // Avoid downloading IndexPart of offloaded timelines.
    1554              :         let mut offloaded_with_prefix = HashSet::new();
    1555              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1556              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1557              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1558              :             } else {
    1559              :                 // We'll take care later of timelines in the manifest without a prefix
    1560              :             }
    1561              :         }
    1562              : 
    1563              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1564              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1565              :         // will kick the secondary in any case and cause a download.
    1566              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1567              : 
    1568              :         let timelines = self
    1569              :             .load_timelines_metadata(
    1570              :                 remote_timeline_ids,
    1571              :                 remote_storage,
    1572              :                 maybe_heatmap_at,
    1573              :                 cancel,
    1574              :             )
    1575              :             .await?;
    1576              : 
    1577              :         Ok(TenantPreload {
    1578              :             tenant_manifest,
    1579              :             timelines: timelines
    1580              :                 .into_iter()
    1581           12 :                 .map(|(id, tl)| (id, Some(tl)))
    1582            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1583              :                 .collect(),
    1584              :         })
    1585              :     }
    1586              : 
    1587          452 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1588          452 :         if !self.conf.load_previous_heatmap {
    1589            0 :             return None;
    1590          452 :         }
    1591          452 : 
    1592          452 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1593          452 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1594            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1595            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1596            0 :                 Err(err) => {
    1597            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1598            0 :                     None
    1599              :                 }
    1600              :             },
    1601          452 :             Err(err) => match err.kind() {
    1602          452 :                 std::io::ErrorKind::NotFound => None,
    1603              :                 _ => {
    1604            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1605            0 :                     None
    1606              :                 }
    1607              :             },
    1608              :         }
    1609          452 :     }
    1610              : 
    1611              :     ///
    1612              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1613              :     ///
    1614              :     /// No background tasks are started as part of this routine.
    1615              :     ///
    1616          452 :     async fn attach(
    1617          452 :         self: &Arc<Tenant>,
    1618          452 :         preload: Option<TenantPreload>,
    1619          452 :         ctx: &RequestContext,
    1620          452 :     ) -> anyhow::Result<()> {
    1621          452 :         span::debug_assert_current_span_has_tenant_id();
    1622          452 : 
    1623          452 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1624              : 
    1625          452 :         let Some(preload) = preload else {
    1626            0 :             anyhow::bail!(
    1627            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1628            0 :             );
    1629              :         };
    1630              : 
    1631          452 :         let mut offloaded_timeline_ids = HashSet::new();
    1632          452 :         let mut offloaded_timelines_list = Vec::new();
    1633          452 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1634            0 :             let timeline_id = timeline_manifest.timeline_id;
    1635            0 :             let offloaded_timeline =
    1636            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1637            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1638            0 :             offloaded_timeline_ids.insert(timeline_id);
    1639            0 :         }
    1640              :         // Complete deletions for offloaded timeline id's from manifest.
    1641              :         // The manifest will be uploaded later in this function.
    1642          452 :         offloaded_timelines_list
    1643          452 :             .retain(|(offloaded_id, offloaded)| {
    1644            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1645            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1646            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1647            0 :                 if delete {
    1648            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1649            0 :                     offloaded.defuse_for_tenant_drop();
    1650            0 :                 }
    1651            0 :                 !delete
    1652          452 :         });
    1653          452 : 
    1654          452 :         let mut timelines_to_resume_deletions = vec![];
    1655          452 : 
    1656          452 :         let mut remote_index_and_client = HashMap::new();
    1657          452 :         let mut timeline_ancestors = HashMap::new();
    1658          452 :         let mut existent_timelines = HashSet::new();
    1659          464 :         for (timeline_id, preload) in preload.timelines {
    1660           12 :             let Some(preload) = preload else { continue };
    1661              :             // This is an invariant of the `preload` function's API
    1662           12 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1663           12 :             let index_part = match preload.index_part {
    1664           12 :                 Ok(i) => {
    1665           12 :                     debug!("remote index part exists for timeline {timeline_id}");
    1666              :                     // We found index_part on the remote, this is the standard case.
    1667           12 :                     existent_timelines.insert(timeline_id);
    1668           12 :                     i
    1669              :                 }
    1670              :                 Err(DownloadError::NotFound) => {
    1671              :                     // There is no index_part on the remote. We only get here
    1672              :                     // if there is some prefix for the timeline in the remote storage.
    1673              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1674              :                     // remnant from a prior incomplete creation or deletion attempt.
    1675              :                     // Delete the local directory as the deciding criterion for a
    1676              :                     // timeline's existence is presence of index_part.
    1677            0 :                     info!(%timeline_id, "index_part not found on remote");
    1678            0 :                     continue;
    1679              :                 }
    1680            0 :                 Err(DownloadError::Fatal(why)) => {
    1681            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1682            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1683            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1684            0 :                     anyhow::bail!(why.to_string());
    1685              :                 }
    1686            0 :                 Err(e) => {
    1687            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1688            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1689            0 :                     // as it might be a temporary issue and we don't want to re-download
    1690            0 :                     // everything after it resolves.
    1691            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1692              : 
    1693            0 :                     existent_timelines.insert(timeline_id);
    1694            0 :                     continue;
    1695              :                 }
    1696              :             };
    1697           12 :             match index_part {
    1698           12 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1699           12 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1700           12 :                     remote_index_and_client.insert(
    1701           12 :                         timeline_id,
    1702           12 :                         (index_part, preload.client, preload.previous_heatmap),
    1703           12 :                     );
    1704           12 :                 }
    1705            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1706            0 :                     info!(
    1707            0 :                         "timeline {} is deleted, picking to resume deletion",
    1708              :                         timeline_id
    1709              :                     );
    1710            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1711              :                 }
    1712              :             }
    1713              :         }
    1714              : 
    1715          452 :         let mut gc_blocks = HashMap::new();
    1716              : 
    1717              :         // For every timeline, download the metadata file, scan the local directory,
    1718              :         // and build a layer map that contains an entry for each remote and local
    1719              :         // layer file.
    1720          452 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1721          464 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1722           12 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1723           12 :                 .remove(&timeline_id)
    1724           12 :                 .expect("just put it in above");
    1725              : 
    1726           12 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1727              :                 // could just filter these away, but it helps while testing
    1728            0 :                 anyhow::ensure!(
    1729            0 :                     !blocking.reasons.is_empty(),
    1730            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1731              :                 );
    1732            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1733            0 :                 assert!(prev.is_none());
    1734           12 :             }
    1735              : 
    1736              :             // TODO again handle early failure
    1737           12 :             let effect = self
    1738           12 :                 .load_remote_timeline(
    1739           12 :                     timeline_id,
    1740           12 :                     index_part,
    1741           12 :                     remote_metadata,
    1742           12 :                     previous_heatmap,
    1743           12 :                     self.get_timeline_resources_for(remote_client),
    1744           12 :                     LoadTimelineCause::Attach,
    1745           12 :                     ctx,
    1746           12 :                 )
    1747           12 :                 .await
    1748           12 :                 .with_context(|| {
    1749            0 :                     format!(
    1750            0 :                         "failed to load remote timeline {} for tenant {}",
    1751            0 :                         timeline_id, self.tenant_shard_id
    1752            0 :                     )
    1753           12 :                 })?;
    1754              : 
    1755           12 :             match effect {
    1756           12 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1757           12 :                     // activation happens later, on Tenant::activate
    1758           12 :                 }
    1759              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1760              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1761            0 :                         timeline,
    1762            0 :                         import_pgdata,
    1763            0 :                         guard,
    1764            0 :                     },
    1765            0 :                 ) => {
    1766            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1767            0 :                         timeline,
    1768            0 :                         import_pgdata,
    1769            0 :                         ActivateTimelineArgs::No,
    1770            0 :                         guard,
    1771            0 :                         ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    1772            0 :                     ));
    1773            0 :                 }
    1774              :             }
    1775              :         }
    1776              : 
    1777              :         // Walk through deleted timelines, resume deletion
    1778          452 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1779            0 :             remote_timeline_client
    1780            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1781            0 :                 .context("init queue stopped")
    1782            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1783              : 
    1784            0 :             DeleteTimelineFlow::resume_deletion(
    1785            0 :                 Arc::clone(self),
    1786            0 :                 timeline_id,
    1787            0 :                 &index_part.metadata,
    1788            0 :                 remote_timeline_client,
    1789            0 :                 ctx,
    1790            0 :             )
    1791            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1792            0 :             .await
    1793            0 :             .context("resume_deletion")
    1794            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1795              :         }
    1796          452 :         let needs_manifest_upload =
    1797          452 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1798          452 :         {
    1799          452 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1800          452 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1801          452 :         }
    1802          452 :         if needs_manifest_upload {
    1803            0 :             self.store_tenant_manifest().await?;
    1804          452 :         }
    1805              : 
    1806              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1807              :         // IndexPart is the source of truth.
    1808          452 :         self.clean_up_timelines(&existent_timelines)?;
    1809              : 
    1810          452 :         self.gc_block.set_scanned(gc_blocks);
    1811          452 : 
    1812          452 :         fail::fail_point!("attach-before-activate", |_| {
    1813            0 :             anyhow::bail!("attach-before-activate");
    1814          452 :         });
    1815          452 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1816              : 
    1817          452 :         info!("Done");
    1818              : 
    1819          452 :         Ok(())
    1820          452 :     }
    1821              : 
    1822              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1823              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1824              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1825          452 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1826          452 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1827              : 
    1828          452 :         let entries = match timelines_dir.read_dir_utf8() {
    1829          452 :             Ok(d) => d,
    1830            0 :             Err(e) => {
    1831            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1832            0 :                     return Ok(());
    1833              :                 } else {
    1834            0 :                     return Err(e).context("list timelines directory for tenant");
    1835              :                 }
    1836              :             }
    1837              :         };
    1838              : 
    1839          468 :         for entry in entries {
    1840           16 :             let entry = entry.context("read timeline dir entry")?;
    1841           16 :             let entry_path = entry.path();
    1842              : 
    1843           16 :             let purge = if crate::is_temporary(entry_path) {
    1844            0 :                 true
    1845              :             } else {
    1846           16 :                 match TimelineId::try_from(entry_path.file_name()) {
    1847           16 :                     Ok(i) => {
    1848           16 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1849           16 :                         !existent_timelines.contains(&i)
    1850              :                     }
    1851            0 :                     Err(e) => {
    1852            0 :                         tracing::warn!(
    1853            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1854              :                         );
    1855              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1856            0 :                         false
    1857              :                     }
    1858              :                 }
    1859              :             };
    1860              : 
    1861           16 :             if purge {
    1862            4 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1863            4 :                 if let Err(e) = match entry.file_type() {
    1864            4 :                     Ok(t) => if t.is_dir() {
    1865            4 :                         std::fs::remove_dir_all(entry_path)
    1866              :                     } else {
    1867            0 :                         std::fs::remove_file(entry_path)
    1868              :                     }
    1869            4 :                     .or_else(fs_ext::ignore_not_found),
    1870            0 :                     Err(e) => Err(e),
    1871              :                 } {
    1872            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1873            4 :                 }
    1874           12 :             }
    1875              :         }
    1876              : 
    1877          452 :         Ok(())
    1878          452 :     }
    1879              : 
    1880              :     /// Get sum of all remote timelines sizes
    1881              :     ///
    1882              :     /// This function relies on the index_part instead of listing the remote storage
    1883            0 :     pub fn remote_size(&self) -> u64 {
    1884            0 :         let mut size = 0;
    1885              : 
    1886            0 :         for timeline in self.list_timelines() {
    1887            0 :             size += timeline.remote_client.get_remote_physical_size();
    1888            0 :         }
    1889              : 
    1890            0 :         size
    1891            0 :     }
    1892              : 
    1893              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1894              :     #[allow(clippy::too_many_arguments)]
    1895              :     async fn load_remote_timeline(
    1896              :         self: &Arc<Self>,
    1897              :         timeline_id: TimelineId,
    1898              :         index_part: IndexPart,
    1899              :         remote_metadata: TimelineMetadata,
    1900              :         previous_heatmap: Option<PreviousHeatmap>,
    1901              :         resources: TimelineResources,
    1902              :         cause: LoadTimelineCause,
    1903              :         ctx: &RequestContext,
    1904              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1905              :         span::debug_assert_current_span_has_tenant_id();
    1906              : 
    1907              :         info!("downloading index file for timeline {}", timeline_id);
    1908              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1909              :             .await
    1910              :             .context("Failed to create new timeline directory")?;
    1911              : 
    1912              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1913              :             let timelines = self.timelines.lock().unwrap();
    1914              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1915            0 :                 || {
    1916            0 :                     anyhow::anyhow!(
    1917            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1918            0 :                     )
    1919            0 :                 },
    1920              :             )?))
    1921              :         } else {
    1922              :             None
    1923              :         };
    1924              : 
    1925              :         self.timeline_init_and_sync(
    1926              :             timeline_id,
    1927              :             resources,
    1928              :             index_part,
    1929              :             remote_metadata,
    1930              :             previous_heatmap,
    1931              :             ancestor,
    1932              :             cause,
    1933              :             ctx,
    1934              :         )
    1935              :         .await
    1936              :     }
    1937              : 
    1938          452 :     async fn load_timelines_metadata(
    1939          452 :         self: &Arc<Tenant>,
    1940          452 :         timeline_ids: HashSet<TimelineId>,
    1941          452 :         remote_storage: &GenericRemoteStorage,
    1942          452 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    1943          452 :         cancel: CancellationToken,
    1944          452 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1945          452 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    1946          452 : 
    1947          452 :         let mut part_downloads = JoinSet::new();
    1948          464 :         for timeline_id in timeline_ids {
    1949           12 :             let cancel_clone = cancel.clone();
    1950           12 : 
    1951           12 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    1952            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    1953            0 :                     heatmap: h,
    1954            0 :                     read_at: hs.1,
    1955            0 :                     end_lsn: None,
    1956            0 :                 })
    1957           12 :             });
    1958           12 :             part_downloads.spawn(
    1959           12 :                 self.load_timeline_metadata(
    1960           12 :                     timeline_id,
    1961           12 :                     remote_storage.clone(),
    1962           12 :                     previous_timeline_heatmap,
    1963           12 :                     cancel_clone,
    1964           12 :                 )
    1965           12 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    1966              :             );
    1967              :         }
    1968              : 
    1969          452 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1970              : 
    1971              :         loop {
    1972          464 :             tokio::select!(
    1973          464 :                 next = part_downloads.join_next() => {
    1974          464 :                     match next {
    1975           12 :                         Some(result) => {
    1976           12 :                             let preload = result.context("join preload task")?;
    1977           12 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1978              :                         },
    1979              :                         None => {
    1980          452 :                             break;
    1981              :                         }
    1982              :                     }
    1983              :                 },
    1984          464 :                 _ = cancel.cancelled() => {
    1985            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1986              :                 }
    1987              :             )
    1988              :         }
    1989              : 
    1990          452 :         Ok(timeline_preloads)
    1991          452 :     }
    1992              : 
    1993           12 :     fn build_timeline_client(
    1994           12 :         &self,
    1995           12 :         timeline_id: TimelineId,
    1996           12 :         remote_storage: GenericRemoteStorage,
    1997           12 :     ) -> RemoteTimelineClient {
    1998           12 :         RemoteTimelineClient::new(
    1999           12 :             remote_storage.clone(),
    2000           12 :             self.deletion_queue_client.clone(),
    2001           12 :             self.conf,
    2002           12 :             self.tenant_shard_id,
    2003           12 :             timeline_id,
    2004           12 :             self.generation,
    2005           12 :             &self.tenant_conf.load().location,
    2006           12 :         )
    2007           12 :     }
    2008              : 
    2009           12 :     fn load_timeline_metadata(
    2010           12 :         self: &Arc<Tenant>,
    2011           12 :         timeline_id: TimelineId,
    2012           12 :         remote_storage: GenericRemoteStorage,
    2013           12 :         previous_heatmap: Option<PreviousHeatmap>,
    2014           12 :         cancel: CancellationToken,
    2015           12 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2016           12 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2017           12 :         async move {
    2018           12 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2019           12 :             debug!("starting index part download");
    2020              : 
    2021           12 :             let index_part = client.download_index_file(&cancel).await;
    2022              : 
    2023           12 :             debug!("finished index part download");
    2024              : 
    2025           12 :             TimelinePreload {
    2026           12 :                 client,
    2027           12 :                 timeline_id,
    2028           12 :                 index_part,
    2029           12 :                 previous_heatmap,
    2030           12 :             }
    2031           12 :         }
    2032           12 :     }
    2033              : 
    2034            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2035            0 :         timeline_id: TimelineId,
    2036            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2037            0 :     ) -> Result<(), TimelineArchivalError> {
    2038            0 :         let children: Vec<TimelineId> = timelines
    2039            0 :             .iter()
    2040            0 :             .filter_map(|(id, entry)| {
    2041            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2042            0 :                     return None;
    2043            0 :                 }
    2044            0 :                 if entry.is_archived() == Some(true) {
    2045            0 :                     return None;
    2046            0 :                 }
    2047            0 :                 Some(*id)
    2048            0 :             })
    2049            0 :             .collect();
    2050            0 : 
    2051            0 :         if !children.is_empty() {
    2052            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2053            0 :         }
    2054            0 :         Ok(())
    2055            0 :     }
    2056              : 
    2057            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2058            0 :         ancestor_timeline_id: TimelineId,
    2059            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2060            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2061            0 :             '_,
    2062            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2063            0 :         >,
    2064            0 :     ) -> Result<(), TimelineArchivalError> {
    2065            0 :         let has_archived_parent =
    2066            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2067            0 :                 ancestor_timeline.is_archived() == Some(true)
    2068            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2069            0 :                 true
    2070              :             } else {
    2071            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2072            0 :                 if cfg!(debug_assertions) {
    2073            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2074            0 :                 }
    2075            0 :                 return Err(TimelineArchivalError::NotFound);
    2076              :             };
    2077            0 :         if has_archived_parent {
    2078            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2079            0 :                 ancestor_timeline_id,
    2080            0 :             ));
    2081            0 :         }
    2082            0 :         Ok(())
    2083            0 :     }
    2084              : 
    2085            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2086            0 :         timeline: &Arc<Timeline>,
    2087            0 :     ) -> Result<(), TimelineArchivalError> {
    2088            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2089            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2090            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2091            0 :                     ancestor_timeline.timeline_id,
    2092            0 :                 ));
    2093            0 :             }
    2094            0 :         }
    2095            0 :         Ok(())
    2096            0 :     }
    2097              : 
    2098              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2099              :     ///
    2100              :     /// Counterpart to [`offload_timeline`].
    2101            0 :     async fn unoffload_timeline(
    2102            0 :         self: &Arc<Self>,
    2103            0 :         timeline_id: TimelineId,
    2104            0 :         broker_client: storage_broker::BrokerClientChannel,
    2105            0 :         ctx: RequestContext,
    2106            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2107            0 :         info!("unoffloading timeline");
    2108              : 
    2109              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2110              :         // We expect callers of this function to ensure this.
    2111            0 :         match self.current_state() {
    2112              :             TenantState::Activating { .. }
    2113              :             | TenantState::Attaching
    2114              :             | TenantState::Broken { .. } => {
    2115            0 :                 panic!("Timeline expected to be active")
    2116              :             }
    2117            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2118            0 :             TenantState::Active => {}
    2119            0 :         }
    2120            0 :         let cancel = self.cancel.clone();
    2121            0 : 
    2122            0 :         // Protect against concurrent attempts to use this TimelineId
    2123            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2124            0 :         let allow_offloaded = true;
    2125            0 :         let _create_guard = self
    2126            0 :             .create_timeline_create_guard(
    2127            0 :                 timeline_id,
    2128            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2129            0 :                 allow_offloaded,
    2130            0 :             )
    2131            0 :             .map_err(|err| match err {
    2132            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2133              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2134            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2135              :                 }
    2136            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2137            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2138            0 :             })?;
    2139              : 
    2140            0 :         let timeline_preload = self
    2141            0 :             .load_timeline_metadata(
    2142            0 :                 timeline_id,
    2143            0 :                 self.remote_storage.clone(),
    2144            0 :                 None,
    2145            0 :                 cancel.clone(),
    2146            0 :             )
    2147            0 :             .await;
    2148              : 
    2149            0 :         let index_part = match timeline_preload.index_part {
    2150            0 :             Ok(index_part) => {
    2151            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2152            0 :                 index_part
    2153              :             }
    2154              :             Err(DownloadError::NotFound) => {
    2155            0 :                 error!(%timeline_id, "index_part not found on remote");
    2156            0 :                 return Err(TimelineArchivalError::NotFound);
    2157              :             }
    2158            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2159            0 :             Err(e) => {
    2160            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2161            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2162            0 :                 return Err(TimelineArchivalError::Other(
    2163            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2164            0 :                 ));
    2165              :             }
    2166              :         };
    2167            0 :         let index_part = match index_part {
    2168            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2169            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2170            0 :                 info!("timeline is deleted according to index_part.json");
    2171            0 :                 return Err(TimelineArchivalError::NotFound);
    2172              :             }
    2173              :         };
    2174            0 :         let remote_metadata = index_part.metadata.clone();
    2175            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2176            0 :         self.load_remote_timeline(
    2177            0 :             timeline_id,
    2178            0 :             index_part,
    2179            0 :             remote_metadata,
    2180            0 :             None,
    2181            0 :             timeline_resources,
    2182            0 :             LoadTimelineCause::Unoffload,
    2183            0 :             &ctx,
    2184            0 :         )
    2185            0 :         .await
    2186            0 :         .with_context(|| {
    2187            0 :             format!(
    2188            0 :                 "failed to load remote timeline {} for tenant {}",
    2189            0 :                 timeline_id, self.tenant_shard_id
    2190            0 :             )
    2191            0 :         })
    2192            0 :         .map_err(TimelineArchivalError::Other)?;
    2193              : 
    2194            0 :         let timeline = {
    2195            0 :             let timelines = self.timelines.lock().unwrap();
    2196            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2197            0 :                 warn!("timeline not available directly after attach");
    2198              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2199              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2200            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2201            0 :                     "timeline not available directly after attach"
    2202            0 :                 )));
    2203              :             };
    2204            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2205            0 :             match offloaded_timelines.remove(&timeline_id) {
    2206            0 :                 Some(offloaded) => {
    2207            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2208            0 :                 }
    2209            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2210              :             }
    2211              : 
    2212            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2213            0 : 
    2214            0 :             Arc::clone(timeline)
    2215            0 :         };
    2216            0 : 
    2217            0 :         // Upload new list of offloaded timelines to S3
    2218            0 :         self.store_tenant_manifest().await?;
    2219              : 
    2220              :         // Activate the timeline (if it makes sense)
    2221            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2222            0 :             let background_jobs_can_start = None;
    2223            0 :             timeline.activate(
    2224            0 :                 self.clone(),
    2225            0 :                 broker_client.clone(),
    2226            0 :                 background_jobs_can_start,
    2227            0 :                 &ctx.with_scope_timeline(&timeline),
    2228            0 :             );
    2229            0 :         }
    2230              : 
    2231            0 :         info!("timeline unoffloading complete");
    2232            0 :         Ok(timeline)
    2233            0 :     }
    2234              : 
    2235            0 :     pub(crate) async fn apply_timeline_archival_config(
    2236            0 :         self: &Arc<Self>,
    2237            0 :         timeline_id: TimelineId,
    2238            0 :         new_state: TimelineArchivalState,
    2239            0 :         broker_client: storage_broker::BrokerClientChannel,
    2240            0 :         ctx: RequestContext,
    2241            0 :     ) -> Result<(), TimelineArchivalError> {
    2242            0 :         info!("setting timeline archival config");
    2243              :         // First part: figure out what is needed to do, and do validation
    2244            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2245            0 :             let timelines = self.timelines.lock().unwrap();
    2246              : 
    2247            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2248            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2249            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2250            0 :                     return Err(TimelineArchivalError::NotFound);
    2251              :                 };
    2252            0 :                 if new_state == TimelineArchivalState::Archived {
    2253              :                     // It's offloaded already, so nothing to do
    2254            0 :                     return Ok(());
    2255            0 :                 }
    2256            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2257            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2258            0 :                         ancestor_timeline_id,
    2259            0 :                         &timelines,
    2260            0 :                         &offloaded_timelines,
    2261            0 :                     )?;
    2262            0 :                 }
    2263            0 :                 break 'outer None;
    2264              :             };
    2265              : 
    2266              :             // Do some validation. We release the timelines lock below, so there is potential
    2267              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2268              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2269            0 :             match new_state {
    2270              :                 TimelineArchivalState::Unarchived => {
    2271            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2272              :                 }
    2273              :                 TimelineArchivalState::Archived => {
    2274            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2275              :                 }
    2276              :             }
    2277            0 :             Some(Arc::clone(timeline))
    2278              :         };
    2279              : 
    2280              :         // Second part: unoffload timeline (if needed)
    2281            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2282            0 :             timeline
    2283              :         } else {
    2284              :             // Turn offloaded timeline into a non-offloaded one
    2285            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2286            0 :                 .await?
    2287              :         };
    2288              : 
    2289              :         // Third part: upload new timeline archival state and block until it is present in S3
    2290            0 :         let upload_needed = match timeline
    2291            0 :             .remote_client
    2292            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2293              :         {
    2294            0 :             Ok(upload_needed) => upload_needed,
    2295            0 :             Err(e) => {
    2296            0 :                 if timeline.cancel.is_cancelled() {
    2297            0 :                     return Err(TimelineArchivalError::Cancelled);
    2298              :                 } else {
    2299            0 :                     return Err(TimelineArchivalError::Other(e));
    2300              :                 }
    2301              :             }
    2302              :         };
    2303              : 
    2304            0 :         if upload_needed {
    2305            0 :             info!("Uploading new state");
    2306              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2307            0 :             let Ok(v) =
    2308            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2309              :             else {
    2310            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2311            0 :                 return Err(TimelineArchivalError::Timeout);
    2312              :             };
    2313            0 :             v.map_err(|e| match e {
    2314            0 :                 WaitCompletionError::NotInitialized(e) => {
    2315            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2316              :                 }
    2317              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2318            0 :                     TimelineArchivalError::Cancelled
    2319              :                 }
    2320            0 :             })?;
    2321            0 :         }
    2322            0 :         Ok(())
    2323            0 :     }
    2324              : 
    2325            4 :     pub fn get_offloaded_timeline(
    2326            4 :         &self,
    2327            4 :         timeline_id: TimelineId,
    2328            4 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2329            4 :         self.timelines_offloaded
    2330            4 :             .lock()
    2331            4 :             .unwrap()
    2332            4 :             .get(&timeline_id)
    2333            4 :             .map(Arc::clone)
    2334            4 :             .ok_or(GetTimelineError::NotFound {
    2335            4 :                 tenant_id: self.tenant_shard_id,
    2336            4 :                 timeline_id,
    2337            4 :             })
    2338            4 :     }
    2339              : 
    2340            8 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2341            8 :         self.tenant_shard_id
    2342            8 :     }
    2343              : 
    2344              :     /// Get Timeline handle for given Neon timeline ID.
    2345              :     /// This function is idempotent. It doesn't change internal state in any way.
    2346          444 :     pub fn get_timeline(
    2347          444 :         &self,
    2348          444 :         timeline_id: TimelineId,
    2349          444 :         active_only: bool,
    2350          444 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2351          444 :         let timelines_accessor = self.timelines.lock().unwrap();
    2352          444 :         let timeline = timelines_accessor
    2353          444 :             .get(&timeline_id)
    2354          444 :             .ok_or(GetTimelineError::NotFound {
    2355          444 :                 tenant_id: self.tenant_shard_id,
    2356          444 :                 timeline_id,
    2357          444 :             })?;
    2358              : 
    2359          440 :         if active_only && !timeline.is_active() {
    2360            0 :             Err(GetTimelineError::NotActive {
    2361            0 :                 tenant_id: self.tenant_shard_id,
    2362            0 :                 timeline_id,
    2363            0 :                 state: timeline.current_state(),
    2364            0 :             })
    2365              :         } else {
    2366          440 :             Ok(Arc::clone(timeline))
    2367              :         }
    2368          444 :     }
    2369              : 
    2370              :     /// Lists timelines the tenant contains.
    2371              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2372            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2373            0 :         self.timelines
    2374            0 :             .lock()
    2375            0 :             .unwrap()
    2376            0 :             .values()
    2377            0 :             .map(Arc::clone)
    2378            0 :             .collect()
    2379            0 :     }
    2380              : 
    2381              :     /// Lists timelines the tenant manages, including offloaded ones.
    2382              :     ///
    2383              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2384            0 :     pub fn list_timelines_and_offloaded(
    2385            0 :         &self,
    2386            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2387            0 :         let timelines = self
    2388            0 :             .timelines
    2389            0 :             .lock()
    2390            0 :             .unwrap()
    2391            0 :             .values()
    2392            0 :             .map(Arc::clone)
    2393            0 :             .collect();
    2394            0 :         let offloaded = self
    2395            0 :             .timelines_offloaded
    2396            0 :             .lock()
    2397            0 :             .unwrap()
    2398            0 :             .values()
    2399            0 :             .map(Arc::clone)
    2400            0 :             .collect();
    2401            0 :         (timelines, offloaded)
    2402            0 :     }
    2403              : 
    2404            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2405            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2406            0 :     }
    2407              : 
    2408              :     /// This is used by tests & import-from-basebackup.
    2409              :     ///
    2410              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2411              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2412              :     ///
    2413              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2414              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2415              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2416              :     /// to the [`Tenant::timelines`].
    2417              :     ///
    2418              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2419          436 :     pub(crate) async fn create_empty_timeline(
    2420          436 :         self: &Arc<Self>,
    2421          436 :         new_timeline_id: TimelineId,
    2422          436 :         initdb_lsn: Lsn,
    2423          436 :         pg_version: u32,
    2424          436 :         ctx: &RequestContext,
    2425          436 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2426          436 :         anyhow::ensure!(
    2427          436 :             self.is_active(),
    2428            0 :             "Cannot create empty timelines on inactive tenant"
    2429              :         );
    2430              : 
    2431              :         // Protect against concurrent attempts to use this TimelineId
    2432          436 :         let create_guard = match self
    2433          436 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2434          436 :             .await?
    2435              :         {
    2436          432 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2437              :             StartCreatingTimelineResult::Idempotent(_) => {
    2438            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2439              :             }
    2440              :         };
    2441              : 
    2442          432 :         let new_metadata = TimelineMetadata::new(
    2443          432 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2444          432 :             // make it valid, before calling finish_creation()
    2445          432 :             Lsn(0),
    2446          432 :             None,
    2447          432 :             None,
    2448          432 :             Lsn(0),
    2449          432 :             initdb_lsn,
    2450          432 :             initdb_lsn,
    2451          432 :             pg_version,
    2452          432 :         );
    2453          432 :         self.prepare_new_timeline(
    2454          432 :             new_timeline_id,
    2455          432 :             &new_metadata,
    2456          432 :             create_guard,
    2457          432 :             initdb_lsn,
    2458          432 :             None,
    2459          432 :             None,
    2460          432 :             ctx,
    2461          432 :         )
    2462          432 :         .await
    2463          436 :     }
    2464              : 
    2465              :     /// Helper for unit tests to create an empty timeline.
    2466              :     ///
    2467              :     /// The timeline is has state value `Active` but its background loops are not running.
    2468              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2469              :     // Our current tests don't need the background loops.
    2470              :     #[cfg(test)]
    2471          416 :     pub async fn create_test_timeline(
    2472          416 :         self: &Arc<Self>,
    2473          416 :         new_timeline_id: TimelineId,
    2474          416 :         initdb_lsn: Lsn,
    2475          416 :         pg_version: u32,
    2476          416 :         ctx: &RequestContext,
    2477          416 :     ) -> anyhow::Result<Arc<Timeline>> {
    2478          416 :         let (uninit_tl, ctx) = self
    2479          416 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2480          416 :             .await?;
    2481          416 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2482          416 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2483              : 
    2484              :         // Setup minimum keys required for the timeline to be usable.
    2485          416 :         let mut modification = tline.begin_modification(initdb_lsn);
    2486          416 :         modification
    2487          416 :             .init_empty_test_timeline()
    2488          416 :             .context("init_empty_test_timeline")?;
    2489          416 :         modification
    2490          416 :             .commit(&ctx)
    2491          416 :             .await
    2492          416 :             .context("commit init_empty_test_timeline modification")?;
    2493              : 
    2494              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2495          416 :         tline.maybe_spawn_flush_loop();
    2496          416 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2497              : 
    2498              :         // Make sure the freeze_and_flush reaches remote storage.
    2499          416 :         tline.remote_client.wait_completion().await.unwrap();
    2500              : 
    2501          416 :         let tl = uninit_tl.finish_creation().await?;
    2502              :         // The non-test code would call tl.activate() here.
    2503          416 :         tl.set_state(TimelineState::Active);
    2504          416 :         Ok(tl)
    2505          416 :     }
    2506              : 
    2507              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2508              :     #[cfg(test)]
    2509              :     #[allow(clippy::too_many_arguments)]
    2510           84 :     pub async fn create_test_timeline_with_layers(
    2511           84 :         self: &Arc<Self>,
    2512           84 :         new_timeline_id: TimelineId,
    2513           84 :         initdb_lsn: Lsn,
    2514           84 :         pg_version: u32,
    2515           84 :         ctx: &RequestContext,
    2516           84 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2517           84 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2518           84 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2519           84 :         end_lsn: Lsn,
    2520           84 :     ) -> anyhow::Result<Arc<Timeline>> {
    2521              :         use checks::check_valid_layermap;
    2522              :         use itertools::Itertools;
    2523              : 
    2524           84 :         let tline = self
    2525           84 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2526           84 :             .await?;
    2527           84 :         tline.force_advance_lsn(end_lsn);
    2528          256 :         for deltas in delta_layer_desc {
    2529          172 :             tline
    2530          172 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2531          172 :                 .await?;
    2532              :         }
    2533          204 :         for (lsn, images) in image_layer_desc {
    2534          120 :             tline
    2535          120 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2536          120 :                 .await?;
    2537              :         }
    2538           92 :         for in_memory in in_memory_layer_desc {
    2539            8 :             tline
    2540            8 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2541            8 :                 .await?;
    2542              :         }
    2543           84 :         let layer_names = tline
    2544           84 :             .layers
    2545           84 :             .read()
    2546           84 :             .await
    2547           84 :             .layer_map()
    2548           84 :             .unwrap()
    2549           84 :             .iter_historic_layers()
    2550          376 :             .map(|layer| layer.layer_name())
    2551           84 :             .collect_vec();
    2552           84 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2553            0 :             bail!("invalid layermap: {err}");
    2554           84 :         }
    2555           84 :         Ok(tline)
    2556           84 :     }
    2557              : 
    2558              :     /// Create a new timeline.
    2559              :     ///
    2560              :     /// Returns the new timeline ID and reference to its Timeline object.
    2561              :     ///
    2562              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2563              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2564              :     #[allow(clippy::too_many_arguments)]
    2565            0 :     pub(crate) async fn create_timeline(
    2566            0 :         self: &Arc<Tenant>,
    2567            0 :         params: CreateTimelineParams,
    2568            0 :         broker_client: storage_broker::BrokerClientChannel,
    2569            0 :         ctx: &RequestContext,
    2570            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2571            0 :         if !self.is_active() {
    2572            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2573            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2574              :             } else {
    2575            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2576            0 :                     "Cannot create timelines on inactive tenant"
    2577            0 :                 )));
    2578              :             }
    2579            0 :         }
    2580              : 
    2581            0 :         let _gate = self
    2582            0 :             .gate
    2583            0 :             .enter()
    2584            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2585              : 
    2586            0 :         let result: CreateTimelineResult = match params {
    2587              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2588            0 :                 new_timeline_id,
    2589            0 :                 existing_initdb_timeline_id,
    2590            0 :                 pg_version,
    2591            0 :             }) => {
    2592            0 :                 self.bootstrap_timeline(
    2593            0 :                     new_timeline_id,
    2594            0 :                     pg_version,
    2595            0 :                     existing_initdb_timeline_id,
    2596            0 :                     ctx,
    2597            0 :                 )
    2598            0 :                 .await?
    2599              :             }
    2600              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2601            0 :                 new_timeline_id,
    2602            0 :                 ancestor_timeline_id,
    2603            0 :                 mut ancestor_start_lsn,
    2604              :             }) => {
    2605            0 :                 let ancestor_timeline = self
    2606            0 :                     .get_timeline(ancestor_timeline_id, false)
    2607            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2608              : 
    2609              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2610              :                 // ready for other purposes either.
    2611            0 :                 if !ancestor_timeline.is_active() {
    2612            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2613            0 :                 }
    2614            0 : 
    2615            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2616            0 :                     info!("tried to branch archived timeline");
    2617            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2618            0 :                 }
    2619              : 
    2620            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2621            0 :                     *lsn = lsn.align();
    2622            0 : 
    2623            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2624            0 :                     if ancestor_ancestor_lsn > *lsn {
    2625              :                         // can we safely just branch from the ancestor instead?
    2626            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2627            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2628            0 :                             lsn,
    2629            0 :                             ancestor_timeline_id,
    2630            0 :                             ancestor_ancestor_lsn,
    2631            0 :                         )));
    2632            0 :                     }
    2633            0 : 
    2634            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2635            0 :                     // to the requested branch point. The repository code itself doesn't
    2636            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2637            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2638            0 :                     // sizes etc. and that would get confused if the previous page versions
    2639            0 :                     // are not in the repository yet.
    2640            0 :                     ancestor_timeline
    2641            0 :                         .wait_lsn(
    2642            0 :                             *lsn,
    2643            0 :                             timeline::WaitLsnWaiter::Tenant,
    2644            0 :                             timeline::WaitLsnTimeout::Default,
    2645            0 :                             ctx,
    2646            0 :                         )
    2647            0 :                         .await
    2648            0 :                         .map_err(|e| match e {
    2649            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2650            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2651              :                             }
    2652            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2653            0 :                         })?;
    2654            0 :                 }
    2655              : 
    2656            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2657            0 :                     .await?
    2658              :             }
    2659            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2660            0 :                 self.create_timeline_import_pgdata(
    2661            0 :                     params,
    2662            0 :                     ActivateTimelineArgs::Yes {
    2663            0 :                         broker_client: broker_client.clone(),
    2664            0 :                     },
    2665            0 :                     ctx,
    2666            0 :                 )
    2667            0 :                 .await?
    2668              :             }
    2669              :         };
    2670              : 
    2671              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2672              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2673              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2674              :         //
    2675              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2676              :         // assume that, because they can see the timeline via API, that the creation is done and
    2677              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2678              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2679              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2680              :         //
    2681              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2682              :         // creation API until it returns success. Only then is durability guaranteed.
    2683            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2684            0 :         result
    2685            0 :             .timeline()
    2686            0 :             .remote_client
    2687            0 :             .wait_completion()
    2688            0 :             .await
    2689            0 :             .map_err(|e| match e {
    2690              :                 WaitCompletionError::NotInitialized(
    2691            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2692            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2693              :                 WaitCompletionError::NotInitialized(_) => {
    2694              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2695            0 :                     debug_assert!(false);
    2696            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2697              :                 }
    2698              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2699            0 :                     CreateTimelineError::ShuttingDown
    2700              :                 }
    2701            0 :             })?;
    2702              : 
    2703              :         // The creating task is responsible for activating the timeline.
    2704              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2705              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2706            0 :         let activated_timeline = match result {
    2707            0 :             CreateTimelineResult::Created(timeline) => {
    2708            0 :                 timeline.activate(
    2709            0 :                     self.clone(),
    2710            0 :                     broker_client,
    2711            0 :                     None,
    2712            0 :                     &ctx.with_scope_timeline(&timeline),
    2713            0 :                 );
    2714            0 :                 timeline
    2715              :             }
    2716            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2717            0 :                 info!(
    2718            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2719              :                 );
    2720            0 :                 timeline
    2721              :             }
    2722            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2723            0 :                 info!(
    2724            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2725              :                 );
    2726            0 :                 timeline
    2727              :             }
    2728              :         };
    2729              : 
    2730            0 :         Ok(activated_timeline)
    2731            0 :     }
    2732              : 
    2733              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2734              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2735              :     /// [`Tenant::timelines`] map when the import completes.
    2736              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2737              :     /// for the response.
    2738            0 :     async fn create_timeline_import_pgdata(
    2739            0 :         self: &Arc<Tenant>,
    2740            0 :         params: CreateTimelineParamsImportPgdata,
    2741            0 :         activate: ActivateTimelineArgs,
    2742            0 :         ctx: &RequestContext,
    2743            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2744            0 :         let CreateTimelineParamsImportPgdata {
    2745            0 :             new_timeline_id,
    2746            0 :             location,
    2747            0 :             idempotency_key,
    2748            0 :         } = params;
    2749            0 : 
    2750            0 :         let started_at = chrono::Utc::now().naive_utc();
    2751              : 
    2752              :         //
    2753              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2754              :         // is the canonical way we do it.
    2755              :         // - create an empty timeline in-memory
    2756              :         // - use its remote_timeline_client to do the upload
    2757              :         // - dispose of the uninit timeline
    2758              :         // - keep the creation guard alive
    2759              : 
    2760            0 :         let timeline_create_guard = match self
    2761            0 :             .start_creating_timeline(
    2762            0 :                 new_timeline_id,
    2763            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2764            0 :                     idempotency_key: idempotency_key.clone(),
    2765            0 :                 }),
    2766            0 :             )
    2767            0 :             .await?
    2768              :         {
    2769            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2770            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2771            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2772              :             }
    2773              :         };
    2774              : 
    2775            0 :         let (mut uninit_timeline, timeline_ctx) = {
    2776            0 :             let this = &self;
    2777            0 :             let initdb_lsn = Lsn(0);
    2778            0 :             async move {
    2779            0 :                 let new_metadata = TimelineMetadata::new(
    2780            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2781            0 :                     // make it valid, before calling finish_creation()
    2782            0 :                     Lsn(0),
    2783            0 :                     None,
    2784            0 :                     None,
    2785            0 :                     Lsn(0),
    2786            0 :                     initdb_lsn,
    2787            0 :                     initdb_lsn,
    2788            0 :                     15,
    2789            0 :                 );
    2790            0 :                 this.prepare_new_timeline(
    2791            0 :                     new_timeline_id,
    2792            0 :                     &new_metadata,
    2793            0 :                     timeline_create_guard,
    2794            0 :                     initdb_lsn,
    2795            0 :                     None,
    2796            0 :                     None,
    2797            0 :                     ctx,
    2798            0 :                 )
    2799            0 :                 .await
    2800            0 :             }
    2801            0 :         }
    2802            0 :         .await?;
    2803              : 
    2804            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2805            0 :             idempotency_key,
    2806            0 :             location,
    2807            0 :             started_at,
    2808            0 :         };
    2809            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2810            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2811            0 :         );
    2812            0 :         uninit_timeline
    2813            0 :             .raw_timeline()
    2814            0 :             .unwrap()
    2815            0 :             .remote_client
    2816            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2817              : 
    2818              :         // wait_completion happens in caller
    2819              : 
    2820            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2821            0 : 
    2822            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2823            0 :             timeline.clone(),
    2824            0 :             index_part,
    2825            0 :             activate,
    2826            0 :             timeline_create_guard,
    2827            0 :             timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    2828            0 :         ));
    2829            0 : 
    2830            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2831            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2832            0 :     }
    2833              : 
    2834              :     #[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))]
    2835              :     async fn create_timeline_import_pgdata_task(
    2836              :         self: Arc<Tenant>,
    2837              :         timeline: Arc<Timeline>,
    2838              :         index_part: import_pgdata::index_part_format::Root,
    2839              :         activate: ActivateTimelineArgs,
    2840              :         timeline_create_guard: TimelineCreateGuard,
    2841              :         ctx: RequestContext,
    2842              :     ) {
    2843              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2844              :         info!("starting");
    2845              :         scopeguard::defer! {info!("exiting")};
    2846              : 
    2847              :         let res = self
    2848              :             .create_timeline_import_pgdata_task_impl(
    2849              :                 timeline,
    2850              :                 index_part,
    2851              :                 activate,
    2852              :                 timeline_create_guard,
    2853              :                 ctx,
    2854              :             )
    2855              :             .await;
    2856              :         if let Err(err) = &res {
    2857              :             error!(?err, "task failed");
    2858              :             // TODO sleep & retry, sensitive to tenant shutdown
    2859              :             // TODO: allow timeline deletion requests => should cancel the task
    2860              :         }
    2861              :     }
    2862              : 
    2863            0 :     async fn create_timeline_import_pgdata_task_impl(
    2864            0 :         self: Arc<Tenant>,
    2865            0 :         timeline: Arc<Timeline>,
    2866            0 :         index_part: import_pgdata::index_part_format::Root,
    2867            0 :         activate: ActivateTimelineArgs,
    2868            0 :         timeline_create_guard: TimelineCreateGuard,
    2869            0 :         ctx: RequestContext,
    2870            0 :     ) -> Result<(), anyhow::Error> {
    2871            0 :         info!("importing pgdata");
    2872            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2873            0 :             .await
    2874            0 :             .context("import")?;
    2875            0 :         info!("import done");
    2876              : 
    2877              :         //
    2878              :         // Reload timeline from remote.
    2879              :         // This proves that the remote state is attachable, and it reuses the code.
    2880              :         //
    2881              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2882              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2883              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2884              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2885              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2886              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2887              :         // to manifest because of the long runtime of this import task.
    2888              : 
    2889              :         //        in theory this shouldn't even .await anything except for coop yield
    2890            0 :         info!("shutting down timeline");
    2891            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2892            0 :         info!("timeline shut down, reloading from remote");
    2893              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2894              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2895              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2896              :         // };
    2897            0 :         let timeline_id = timeline.timeline_id;
    2898            0 : 
    2899            0 :         // load from object storage like Tenant::attach does
    2900            0 :         let resources = self.build_timeline_resources(timeline_id);
    2901            0 :         let index_part = resources
    2902            0 :             .remote_client
    2903            0 :             .download_index_file(&self.cancel)
    2904            0 :             .await?;
    2905            0 :         let index_part = match index_part {
    2906              :             MaybeDeletedIndexPart::Deleted(_) => {
    2907              :                 // likely concurrent delete call, cplane should prevent this
    2908            0 :                 anyhow::bail!(
    2909            0 :                     "index part says deleted but we are not done creating yet, this should not happen but"
    2910            0 :                 )
    2911              :             }
    2912            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2913            0 :         };
    2914            0 :         let metadata = index_part.metadata.clone();
    2915            0 :         self
    2916            0 :             .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
    2917            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2918            0 :             .await?
    2919            0 :             .ready_to_activate()
    2920            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2921              : 
    2922            0 :         anyhow::Ok(())
    2923            0 :     }
    2924              : 
    2925            0 :     pub(crate) async fn delete_timeline(
    2926            0 :         self: Arc<Self>,
    2927            0 :         timeline_id: TimelineId,
    2928            0 :     ) -> Result<(), DeleteTimelineError> {
    2929            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2930              : 
    2931            0 :         Ok(())
    2932            0 :     }
    2933              : 
    2934              :     /// perform one garbage collection iteration, removing old data files from disk.
    2935              :     /// this function is periodically called by gc task.
    2936              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2937              :     ///
    2938              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2939              :     ///
    2940              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2941              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2942              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2943              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2944              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2945              :     /// requires more history to be retained.
    2946              :     //
    2947         1508 :     pub(crate) async fn gc_iteration(
    2948         1508 :         &self,
    2949         1508 :         target_timeline_id: Option<TimelineId>,
    2950         1508 :         horizon: u64,
    2951         1508 :         pitr: Duration,
    2952         1508 :         cancel: &CancellationToken,
    2953         1508 :         ctx: &RequestContext,
    2954         1508 :     ) -> Result<GcResult, GcError> {
    2955         1508 :         // Don't start doing work during shutdown
    2956         1508 :         if let TenantState::Stopping { .. } = self.current_state() {
    2957            0 :             return Ok(GcResult::default());
    2958         1508 :         }
    2959         1508 : 
    2960         1508 :         // there is a global allowed_error for this
    2961         1508 :         if !self.is_active() {
    2962            0 :             return Err(GcError::NotActive);
    2963         1508 :         }
    2964         1508 : 
    2965         1508 :         {
    2966         1508 :             let conf = self.tenant_conf.load();
    2967         1508 : 
    2968         1508 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2969         1508 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2970         1508 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2971         1508 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2972         1508 :             if !conf.location.may_delete_layers_hint() {
    2973            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2974            0 :                 return Ok(GcResult::default());
    2975         1508 :             }
    2976         1508 : 
    2977         1508 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2978         1500 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2979         1500 :                 return Ok(GcResult::default());
    2980            8 :             }
    2981              :         }
    2982              : 
    2983            8 :         let _guard = match self.gc_block.start().await {
    2984            8 :             Ok(guard) => guard,
    2985            0 :             Err(reasons) => {
    2986            0 :                 info!("Skipping GC: {reasons}");
    2987            0 :                 return Ok(GcResult::default());
    2988              :             }
    2989              :         };
    2990              : 
    2991            8 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2992            8 :             .await
    2993         1508 :     }
    2994              : 
    2995              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    2996              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    2997              :     /// immediate L0 compaction.
    2998              :     ///
    2999              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    3000            0 :     async fn compaction_iteration(
    3001            0 :         self: &Arc<Self>,
    3002            0 :         cancel: &CancellationToken,
    3003            0 :         ctx: &RequestContext,
    3004            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    3005            0 :         // Don't compact inactive tenants.
    3006            0 :         if !self.is_active() {
    3007            0 :             return Ok(CompactionOutcome::Skipped);
    3008            0 :         }
    3009            0 : 
    3010            0 :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    3011            0 :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    3012            0 :         let location = self.tenant_conf.load().location;
    3013            0 :         if !location.may_upload_layers_hint() {
    3014            0 :             info!("skipping compaction in location state {location:?}");
    3015            0 :             return Ok(CompactionOutcome::Skipped);
    3016            0 :         }
    3017            0 : 
    3018            0 :         // Don't compact if the circuit breaker is tripped.
    3019            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3020            0 :             info!("skipping compaction due to previous failures");
    3021            0 :             return Ok(CompactionOutcome::Skipped);
    3022            0 :         }
    3023            0 : 
    3024            0 :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3025            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3026            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3027            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3028            0 : 
    3029            0 :         {
    3030            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3031            0 :             let timelines = self.timelines.lock().unwrap();
    3032            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3033              :                 // Skip inactive timelines.
    3034            0 :                 if !timeline.is_active() {
    3035            0 :                     continue;
    3036            0 :                 }
    3037            0 : 
    3038            0 :                 // Schedule the timeline for compaction.
    3039            0 :                 compact.push(timeline.clone());
    3040              : 
    3041              :                 // Schedule the timeline for offloading if eligible.
    3042            0 :                 let can_offload = offload_enabled
    3043            0 :                     && timeline.can_offload().0
    3044            0 :                     && !timelines
    3045            0 :                         .iter()
    3046            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3047            0 :                 if can_offload {
    3048            0 :                     offload.insert(timeline_id);
    3049            0 :                 }
    3050              :             }
    3051              :         } // release timelines lock
    3052              : 
    3053            0 :         for timeline in &compact {
    3054              :             // Collect L0 counts. Can't await while holding lock above.
    3055            0 :             if let Ok(lm) = timeline.layers.read().await.layer_map() {
    3056            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3057            0 :             }
    3058              :         }
    3059              : 
    3060              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3061              :         // bound read amplification.
    3062              :         //
    3063              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3064              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3065              :         // splitting L0 and image/GC compaction to separate background jobs.
    3066            0 :         if self.get_compaction_l0_first() {
    3067            0 :             let compaction_threshold = self.get_compaction_threshold();
    3068            0 :             let compact_l0 = compact
    3069            0 :                 .iter()
    3070            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3071            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3072            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3073            0 :                 .rev()
    3074            0 :                 .map(|(tli, _)| tli.clone())
    3075            0 :                 .collect_vec();
    3076            0 : 
    3077            0 :             let mut has_pending_l0 = false;
    3078            0 :             for timeline in compact_l0 {
    3079            0 :                 let ctx = &ctx.with_scope_timeline(&timeline);
    3080            0 :                 let outcome = timeline
    3081            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3082            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3083            0 :                     .await
    3084            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3085            0 :                 match outcome {
    3086            0 :                     CompactionOutcome::Done => {}
    3087            0 :                     CompactionOutcome::Skipped => {}
    3088            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3089            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3090              :                 }
    3091              :             }
    3092            0 :             if has_pending_l0 {
    3093            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3094            0 :             }
    3095            0 :         }
    3096              : 
    3097              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated
    3098              :         // more L0 layers, they may also be compacted here.
    3099              :         //
    3100              :         // NB: image compaction may yield if there is pending L0 compaction.
    3101              :         //
    3102              :         // TODO: it will only yield if there is pending L0 compaction on the same timeline. If a
    3103              :         // different timeline needs compaction, it won't. It should check `l0_compaction_trigger`.
    3104              :         // We leave this for a later PR.
    3105              :         //
    3106              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3107              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3108            0 :         let mut has_pending = false;
    3109            0 :         for timeline in compact {
    3110            0 :             if !timeline.is_active() {
    3111            0 :                 continue;
    3112            0 :             }
    3113            0 :             let ctx = &ctx.with_scope_timeline(&timeline);
    3114              : 
    3115            0 :             let mut outcome = timeline
    3116            0 :                 .compact(cancel, EnumSet::default(), ctx)
    3117            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3118            0 :                 .await
    3119            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3120              : 
    3121              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3122            0 :             if outcome == CompactionOutcome::Done {
    3123            0 :                 let queue = {
    3124            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3125            0 :                     guard
    3126            0 :                         .entry(timeline.timeline_id)
    3127            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3128            0 :                         .clone()
    3129            0 :                 };
    3130            0 :                 outcome = queue
    3131            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3132            0 :                     .instrument(
    3133            0 :                         info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
    3134              :                     )
    3135            0 :                     .await?;
    3136            0 :             }
    3137              : 
    3138              :             // If we're done compacting, offload the timeline if requested.
    3139            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3140            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3141            0 :                 offload_timeline(self, &timeline)
    3142            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3143            0 :                     .await
    3144            0 :                     .or_else(|err| match err {
    3145              :                         // Ignore this, we likely raced with unarchival.
    3146            0 :                         OffloadError::NotArchived => Ok(()),
    3147            0 :                         err => Err(err),
    3148            0 :                     })?;
    3149            0 :             }
    3150              : 
    3151            0 :             match outcome {
    3152            0 :                 CompactionOutcome::Done => {}
    3153            0 :                 CompactionOutcome::Skipped => {}
    3154            0 :                 CompactionOutcome::Pending => has_pending = true,
    3155              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3156              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3157            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3158              :             }
    3159              :         }
    3160              : 
    3161              :         // Success! Untrip the breaker if necessary.
    3162            0 :         self.compaction_circuit_breaker
    3163            0 :             .lock()
    3164            0 :             .unwrap()
    3165            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3166            0 : 
    3167            0 :         match has_pending {
    3168            0 :             true => Ok(CompactionOutcome::Pending),
    3169            0 :             false => Ok(CompactionOutcome::Done),
    3170              :         }
    3171            0 :     }
    3172              : 
    3173              :     /// Trips the compaction circuit breaker if appropriate.
    3174            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3175            0 :         match err {
    3176            0 :             err if err.is_cancel() => {}
    3177            0 :             CompactionError::ShuttingDown => (),
    3178              :             // Offload failures don't trip the circuit breaker, since they're cheap to retry and
    3179              :             // shouldn't block compaction.
    3180            0 :             CompactionError::Offload(_) => {}
    3181            0 :             CompactionError::CollectKeySpaceError(err) => {
    3182            0 :                 // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
    3183            0 :                 self.compaction_circuit_breaker
    3184            0 :                     .lock()
    3185            0 :                     .unwrap()
    3186            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3187            0 :             }
    3188            0 :             CompactionError::Other(err) => {
    3189            0 :                 self.compaction_circuit_breaker
    3190            0 :                     .lock()
    3191            0 :                     .unwrap()
    3192            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3193            0 :             }
    3194            0 :             CompactionError::AlreadyRunning(_) => {}
    3195              :         }
    3196            0 :     }
    3197              : 
    3198              :     /// Cancel scheduled compaction tasks
    3199            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3200            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3201            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3202            0 :             q.cancel_scheduled();
    3203            0 :         }
    3204            0 :     }
    3205              : 
    3206            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3207            0 :         &self,
    3208            0 :         timeline_id: TimelineId,
    3209            0 :     ) -> Vec<CompactInfoResponse> {
    3210            0 :         let res = {
    3211            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3212            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3213              :         };
    3214            0 :         let Some((running, remaining)) = res else {
    3215            0 :             return Vec::new();
    3216              :         };
    3217            0 :         let mut result = Vec::new();
    3218            0 :         if let Some((id, running)) = running {
    3219            0 :             result.extend(running.into_compact_info_resp(id, true));
    3220            0 :         }
    3221            0 :         for (id, job) in remaining {
    3222            0 :             result.extend(job.into_compact_info_resp(id, false));
    3223            0 :         }
    3224            0 :         result
    3225            0 :     }
    3226              : 
    3227              :     /// Schedule a compaction task for a timeline.
    3228            0 :     pub(crate) async fn schedule_compaction(
    3229            0 :         &self,
    3230            0 :         timeline_id: TimelineId,
    3231            0 :         options: CompactOptions,
    3232            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3233            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3234            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3235            0 :         let q = guard
    3236            0 :             .entry(timeline_id)
    3237            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3238            0 :         q.schedule_manual_compaction(options, Some(tx));
    3239            0 :         Ok(rx)
    3240            0 :     }
    3241              : 
    3242              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3243            0 :     async fn housekeeping(&self) {
    3244            0 :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3245            0 :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3246            0 :         let timelines = self
    3247            0 :             .timelines
    3248            0 :             .lock()
    3249            0 :             .unwrap()
    3250            0 :             .values()
    3251            0 :             .filter(|tli| tli.is_active())
    3252            0 :             .cloned()
    3253            0 :             .collect_vec();
    3254              : 
    3255            0 :         for timeline in timelines {
    3256            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3257              :         }
    3258              : 
    3259              :         // Shut down walredo if idle.
    3260              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3261            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3262            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3263            0 :         }
    3264            0 :     }
    3265              : 
    3266            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3267            0 :         let timelines = self.timelines.lock().unwrap();
    3268            0 :         !timelines
    3269            0 :             .iter()
    3270            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3271            0 :     }
    3272              : 
    3273         3476 :     pub fn current_state(&self) -> TenantState {
    3274         3476 :         self.state.borrow().clone()
    3275         3476 :     }
    3276              : 
    3277         1952 :     pub fn is_active(&self) -> bool {
    3278         1952 :         self.current_state() == TenantState::Active
    3279         1952 :     }
    3280              : 
    3281            0 :     pub fn generation(&self) -> Generation {
    3282            0 :         self.generation
    3283            0 :     }
    3284              : 
    3285            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3286            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3287            0 :     }
    3288              : 
    3289              :     /// Changes tenant status to active, unless shutdown was already requested.
    3290              :     ///
    3291              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3292              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3293            0 :     fn activate(
    3294            0 :         self: &Arc<Self>,
    3295            0 :         broker_client: BrokerClientChannel,
    3296            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3297            0 :         ctx: &RequestContext,
    3298            0 :     ) {
    3299            0 :         span::debug_assert_current_span_has_tenant_id();
    3300            0 : 
    3301            0 :         let mut activating = false;
    3302            0 :         self.state.send_modify(|current_state| {
    3303              :             use pageserver_api::models::ActivatingFrom;
    3304            0 :             match &*current_state {
    3305              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3306            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3307              :                 }
    3308            0 :                 TenantState::Attaching => {
    3309            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3310            0 :                 }
    3311            0 :             }
    3312            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3313            0 :             activating = true;
    3314            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3315            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3316            0 :         });
    3317            0 : 
    3318            0 :         if activating {
    3319            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3320            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3321            0 :             let timelines_to_activate = timelines_accessor
    3322            0 :                 .values()
    3323            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3324            0 : 
    3325            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3326            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3327            0 : 
    3328            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3329            0 :             // down when they notice that the tenant is inactive.
    3330            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3331            0 : 
    3332            0 :             let mut activated_timelines = 0;
    3333              : 
    3334            0 :             for timeline in timelines_to_activate {
    3335            0 :                 timeline.activate(
    3336            0 :                     self.clone(),
    3337            0 :                     broker_client.clone(),
    3338            0 :                     background_jobs_can_start,
    3339            0 :                     &ctx.with_scope_timeline(timeline),
    3340            0 :                 );
    3341            0 :                 activated_timelines += 1;
    3342            0 :             }
    3343              : 
    3344            0 :             self.state.send_modify(move |current_state| {
    3345            0 :                 assert!(
    3346            0 :                     matches!(current_state, TenantState::Activating(_)),
    3347            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3348              :                 );
    3349            0 :                 *current_state = TenantState::Active;
    3350            0 : 
    3351            0 :                 let elapsed = self.constructed_at.elapsed();
    3352            0 :                 let total_timelines = timelines_accessor.len();
    3353            0 : 
    3354            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3355            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3356            0 :                 info!(
    3357            0 :                     since_creation_millis = elapsed.as_millis(),
    3358            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3359            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3360            0 :                     activated_timelines,
    3361            0 :                     total_timelines,
    3362            0 :                     post_state = <&'static str>::from(&*current_state),
    3363            0 :                     "activation attempt finished"
    3364              :                 );
    3365              : 
    3366            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3367            0 :             });
    3368            0 :         }
    3369            0 :     }
    3370              : 
    3371              :     /// Shutdown the tenant and join all of the spawned tasks.
    3372              :     ///
    3373              :     /// The method caters for all use-cases:
    3374              :     /// - pageserver shutdown (freeze_and_flush == true)
    3375              :     /// - detach + ignore (freeze_and_flush == false)
    3376              :     ///
    3377              :     /// This will attempt to shutdown even if tenant is broken.
    3378              :     ///
    3379              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3380              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3381              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3382              :     /// the ongoing shutdown.
    3383           12 :     async fn shutdown(
    3384           12 :         &self,
    3385           12 :         shutdown_progress: completion::Barrier,
    3386           12 :         shutdown_mode: timeline::ShutdownMode,
    3387           12 :     ) -> Result<(), completion::Barrier> {
    3388           12 :         span::debug_assert_current_span_has_tenant_id();
    3389              : 
    3390              :         // Set tenant (and its timlines) to Stoppping state.
    3391              :         //
    3392              :         // Since we can only transition into Stopping state after activation is complete,
    3393              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3394              :         //
    3395              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3396              :         // 1. Lock out any new requests to the tenants.
    3397              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3398              :         // 3. Signal cancellation for other tenant background loops.
    3399              :         // 4. ???
    3400              :         //
    3401              :         // The waiting for the cancellation is not done uniformly.
    3402              :         // We certainly wait for WAL receivers to shut down.
    3403              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3404              :         // But the tenant background loops are joined-on in our caller.
    3405              :         // It's mesed up.
    3406              :         // we just ignore the failure to stop
    3407              : 
    3408              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3409              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3410              :         // is very slow.
    3411           12 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3412            0 :             self.cancel.cancel();
    3413            0 : 
    3414            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3415            0 :             // are children of ours, so their flush loops will have shut down already
    3416            0 :             timeline::ShutdownMode::Hard
    3417              :         } else {
    3418           12 :             shutdown_mode
    3419              :         };
    3420              : 
    3421           12 :         match self.set_stopping(shutdown_progress, false, false).await {
    3422           12 :             Ok(()) => {}
    3423            0 :             Err(SetStoppingError::Broken) => {
    3424            0 :                 // assume that this is acceptable
    3425            0 :             }
    3426            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3427            0 :                 // give caller the option to wait for this this shutdown
    3428            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3429            0 :                 return Err(other);
    3430              :             }
    3431              :         };
    3432              : 
    3433           12 :         let mut js = tokio::task::JoinSet::new();
    3434           12 :         {
    3435           12 :             let timelines = self.timelines.lock().unwrap();
    3436           12 :             timelines.values().for_each(|timeline| {
    3437           12 :                 let timeline = Arc::clone(timeline);
    3438           12 :                 let timeline_id = timeline.timeline_id;
    3439           12 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3440           12 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3441           12 :             });
    3442           12 :         }
    3443           12 :         {
    3444           12 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3445           12 :             timelines_offloaded.values().for_each(|timeline| {
    3446            0 :                 timeline.defuse_for_tenant_drop();
    3447           12 :             });
    3448           12 :         }
    3449           12 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3450           12 :         tracing::info!("Waiting for timelines...");
    3451           24 :         while let Some(res) = js.join_next().await {
    3452            0 :             match res {
    3453           12 :                 Ok(()) => {}
    3454            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3455            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3456            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3457              :             }
    3458              :         }
    3459              : 
    3460           12 :         if let ShutdownMode::Reload = shutdown_mode {
    3461            0 :             tracing::info!("Flushing deletion queue");
    3462            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3463            0 :                 match e {
    3464            0 :                     DeletionQueueError::ShuttingDown => {
    3465            0 :                         // This is the only error we expect for now. In the future, if more error
    3466            0 :                         // variants are added, we should handle them here.
    3467            0 :                     }
    3468              :                 }
    3469            0 :             }
    3470           12 :         }
    3471              : 
    3472              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3473              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3474           12 :         tracing::debug!("Cancelling CancellationToken");
    3475           12 :         self.cancel.cancel();
    3476           12 : 
    3477           12 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3478           12 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3479           12 :         //
    3480           12 :         // this will additionally shutdown and await all timeline tasks.
    3481           12 :         tracing::debug!("Waiting for tasks...");
    3482           12 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3483              : 
    3484           12 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3485           12 :             walredo_mgr.shutdown().await;
    3486            0 :         }
    3487              : 
    3488              :         // Wait for any in-flight operations to complete
    3489           12 :         self.gate.close().await;
    3490              : 
    3491           12 :         remove_tenant_metrics(&self.tenant_shard_id);
    3492           12 : 
    3493           12 :         Ok(())
    3494           12 :     }
    3495              : 
    3496              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3497              :     ///
    3498              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3499              :     ///
    3500              :     /// This function is not cancel-safe!
    3501              :     ///
    3502              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3503              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3504           12 :     async fn set_stopping(
    3505           12 :         &self,
    3506           12 :         progress: completion::Barrier,
    3507           12 :         _allow_transition_from_loading: bool,
    3508           12 :         allow_transition_from_attaching: bool,
    3509           12 :     ) -> Result<(), SetStoppingError> {
    3510           12 :         let mut rx = self.state.subscribe();
    3511           12 : 
    3512           12 :         // cannot stop before we're done activating, so wait out until we're done activating
    3513           12 :         rx.wait_for(|state| match state {
    3514            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3515              :             TenantState::Activating(_) | TenantState::Attaching => {
    3516            0 :                 info!(
    3517            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3518            0 :                     <&'static str>::from(state)
    3519              :                 );
    3520            0 :                 false
    3521              :             }
    3522           12 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3523           12 :         })
    3524           12 :         .await
    3525           12 :         .expect("cannot drop self.state while on a &self method");
    3526           12 : 
    3527           12 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3528           12 :         let mut err = None;
    3529           12 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3530              :             TenantState::Activating(_) => {
    3531            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3532              :             }
    3533              :             TenantState::Attaching => {
    3534            0 :                 if !allow_transition_from_attaching {
    3535            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3536            0 :                 };
    3537            0 :                 *current_state = TenantState::Stopping { progress };
    3538            0 :                 true
    3539              :             }
    3540              :             TenantState::Active => {
    3541              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3542              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3543              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3544           12 :                 *current_state = TenantState::Stopping { progress };
    3545           12 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3546           12 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3547           12 :                 true
    3548              :             }
    3549            0 :             TenantState::Broken { reason, .. } => {
    3550            0 :                 info!(
    3551            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3552              :                 );
    3553            0 :                 err = Some(SetStoppingError::Broken);
    3554            0 :                 false
    3555              :             }
    3556            0 :             TenantState::Stopping { progress } => {
    3557            0 :                 info!("Tenant is already in Stopping state");
    3558            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3559            0 :                 false
    3560              :             }
    3561           12 :         });
    3562           12 :         match (stopping, err) {
    3563           12 :             (true, None) => {} // continue
    3564            0 :             (false, Some(err)) => return Err(err),
    3565            0 :             (true, Some(_)) => unreachable!(
    3566            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3567            0 :             ),
    3568            0 :             (false, None) => unreachable!(
    3569            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3570            0 :             ),
    3571              :         }
    3572              : 
    3573           12 :         let timelines_accessor = self.timelines.lock().unwrap();
    3574           12 :         let not_broken_timelines = timelines_accessor
    3575           12 :             .values()
    3576           12 :             .filter(|timeline| !timeline.is_broken());
    3577           24 :         for timeline in not_broken_timelines {
    3578           12 :             timeline.set_state(TimelineState::Stopping);
    3579           12 :         }
    3580           12 :         Ok(())
    3581           12 :     }
    3582              : 
    3583              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3584              :     /// `remove_tenant_from_memory`
    3585              :     ///
    3586              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3587              :     ///
    3588              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3589            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3590            0 :         let mut rx = self.state.subscribe();
    3591            0 : 
    3592            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3593            0 :         // So, wait until it's done.
    3594            0 :         rx.wait_for(|state| match state {
    3595              :             TenantState::Activating(_) | TenantState::Attaching => {
    3596            0 :                 info!(
    3597            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3598            0 :                     <&'static str>::from(state)
    3599              :                 );
    3600            0 :                 false
    3601              :             }
    3602            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3603            0 :         })
    3604            0 :         .await
    3605            0 :         .expect("cannot drop self.state while on a &self method");
    3606            0 : 
    3607            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3608            0 :         self.set_broken_no_wait(reason)
    3609            0 :     }
    3610              : 
    3611            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3612            0 :         let reason = reason.to_string();
    3613            0 :         self.state.send_modify(|current_state| {
    3614            0 :             match *current_state {
    3615              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3616            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3617              :                 }
    3618              :                 TenantState::Active => {
    3619            0 :                     if cfg!(feature = "testing") {
    3620            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3621            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3622              :                     } else {
    3623            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3624              :                     }
    3625              :                 }
    3626              :                 TenantState::Broken { .. } => {
    3627            0 :                     warn!("Tenant is already in Broken state");
    3628              :                 }
    3629              :                 // This is the only "expected" path, any other path is a bug.
    3630              :                 TenantState::Stopping { .. } => {
    3631            0 :                     warn!(
    3632            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3633              :                         reason
    3634              :                     );
    3635            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3636              :                 }
    3637              :            }
    3638            0 :         });
    3639            0 :     }
    3640              : 
    3641            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3642            0 :         self.state.subscribe()
    3643            0 :     }
    3644              : 
    3645              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3646              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3647            0 :     pub(crate) fn activate_now(&self) {
    3648            0 :         self.activate_now_sem.add_permits(1);
    3649            0 :     }
    3650              : 
    3651            0 :     pub(crate) async fn wait_to_become_active(
    3652            0 :         &self,
    3653            0 :         timeout: Duration,
    3654            0 :     ) -> Result<(), GetActiveTenantError> {
    3655            0 :         let mut receiver = self.state.subscribe();
    3656              :         loop {
    3657            0 :             let current_state = receiver.borrow_and_update().clone();
    3658            0 :             match current_state {
    3659              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3660              :                     // in these states, there's a chance that we can reach ::Active
    3661            0 :                     self.activate_now();
    3662            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3663            0 :                         Ok(r) => {
    3664            0 :                             r.map_err(
    3665            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3666              :                                 // Tenant existed but was dropped: report it as non-existent
    3667            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3668            0 :                         )?
    3669              :                         }
    3670              :                         Err(TimeoutCancellableError::Cancelled) => {
    3671            0 :                             return Err(GetActiveTenantError::Cancelled);
    3672              :                         }
    3673              :                         Err(TimeoutCancellableError::Timeout) => {
    3674            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3675            0 :                                 latest_state: Some(self.current_state()),
    3676            0 :                                 wait_time: timeout,
    3677            0 :                             });
    3678              :                         }
    3679              :                     }
    3680              :                 }
    3681              :                 TenantState::Active { .. } => {
    3682            0 :                     return Ok(());
    3683              :                 }
    3684            0 :                 TenantState::Broken { reason, .. } => {
    3685            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3686            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3687            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3688              :                 }
    3689              :                 TenantState::Stopping { .. } => {
    3690              :                     // There's no chance the tenant can transition back into ::Active
    3691            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3692              :                 }
    3693              :             }
    3694              :         }
    3695            0 :     }
    3696              : 
    3697            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3698            0 :         self.tenant_conf.load().location.attach_mode
    3699            0 :     }
    3700              : 
    3701              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3702              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3703              :     /// rare external API calls, like a reconciliation at startup.
    3704            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3705            0 :         let conf = self.tenant_conf.load();
    3706              : 
    3707            0 :         let location_config_mode = match conf.location.attach_mode {
    3708            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3709            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3710            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3711              :         };
    3712              : 
    3713              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3714            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3715            0 : 
    3716            0 :         models::LocationConfig {
    3717            0 :             mode: location_config_mode,
    3718            0 :             generation: self.generation.into(),
    3719            0 :             secondary_conf: None,
    3720            0 :             shard_number: self.shard_identity.number.0,
    3721            0 :             shard_count: self.shard_identity.count.literal(),
    3722            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3723            0 :             tenant_conf: tenant_config,
    3724            0 :         }
    3725            0 :     }
    3726              : 
    3727            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3728            0 :         &self.tenant_shard_id
    3729            0 :     }
    3730              : 
    3731            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3732            0 :         self.shard_identity.stripe_size
    3733            0 :     }
    3734              : 
    3735            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3736            0 :         self.generation
    3737            0 :     }
    3738              : 
    3739              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3740              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3741              :     /// resetting this tenant to a valid state if we fail.
    3742            0 :     pub(crate) async fn split_prepare(
    3743            0 :         &self,
    3744            0 :         child_shards: &Vec<TenantShardId>,
    3745            0 :     ) -> anyhow::Result<()> {
    3746            0 :         let (timelines, offloaded) = {
    3747            0 :             let timelines = self.timelines.lock().unwrap();
    3748            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3749            0 :             (timelines.clone(), offloaded.clone())
    3750            0 :         };
    3751            0 :         let timelines_iter = timelines
    3752            0 :             .values()
    3753            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3754            0 :             .chain(
    3755            0 :                 offloaded
    3756            0 :                     .values()
    3757            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3758            0 :             );
    3759            0 :         for timeline in timelines_iter {
    3760              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3761              :             // to ensure that they do not start a split if currently in the process of doing these.
    3762              : 
    3763            0 :             let timeline_id = timeline.timeline_id();
    3764              : 
    3765            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3766              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3767              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3768              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3769            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3770            0 :                 timeline
    3771            0 :                     .remote_client
    3772            0 :                     .schedule_index_upload_for_file_changes()?;
    3773            0 :                 timeline.remote_client.wait_completion().await?;
    3774            0 :             }
    3775              : 
    3776            0 :             let remote_client = match timeline {
    3777            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3778            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3779            0 :                     let remote_client = self
    3780            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3781            0 :                     Arc::new(remote_client)
    3782              :                 }
    3783              :             };
    3784              : 
    3785              :             // Shut down the timeline's remote client: this means that the indices we write
    3786              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3787            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3788            0 :             remote_client.shutdown().await;
    3789              : 
    3790              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3791              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3792              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3793              :             // we use here really is the remotely persistent one).
    3794            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3795            0 :             let result = remote_client
    3796            0 :                 .download_index_file(&self.cancel)
    3797            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))
    3798            0 :                 .await?;
    3799            0 :             let index_part = match result {
    3800              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3801            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3802              :                 }
    3803            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3804              :             };
    3805              : 
    3806            0 :             for child_shard in child_shards {
    3807            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3808            0 :                 upload_index_part(
    3809            0 :                     &self.remote_storage,
    3810            0 :                     child_shard,
    3811            0 :                     &timeline_id,
    3812            0 :                     self.generation,
    3813            0 :                     &index_part,
    3814            0 :                     &self.cancel,
    3815            0 :                 )
    3816            0 :                 .await?;
    3817              :             }
    3818              :         }
    3819              : 
    3820            0 :         let tenant_manifest = self.build_tenant_manifest();
    3821            0 :         for child_shard in child_shards {
    3822            0 :             tracing::info!(
    3823            0 :                 "Uploading tenant manifest for child {}",
    3824            0 :                 child_shard.to_index()
    3825              :             );
    3826            0 :             upload_tenant_manifest(
    3827            0 :                 &self.remote_storage,
    3828            0 :                 child_shard,
    3829            0 :                 self.generation,
    3830            0 :                 &tenant_manifest,
    3831            0 :                 &self.cancel,
    3832            0 :             )
    3833            0 :             .await?;
    3834              :         }
    3835              : 
    3836            0 :         Ok(())
    3837            0 :     }
    3838              : 
    3839            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3840            0 :         let mut result = TopTenantShardItem {
    3841            0 :             id: self.tenant_shard_id,
    3842            0 :             resident_size: 0,
    3843            0 :             physical_size: 0,
    3844            0 :             max_logical_size: 0,
    3845            0 :             max_logical_size_per_shard: 0,
    3846            0 :         };
    3847              : 
    3848            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3849            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3850            0 : 
    3851            0 :             result.physical_size += timeline
    3852            0 :                 .remote_client
    3853            0 :                 .metrics
    3854            0 :                 .remote_physical_size_gauge
    3855            0 :                 .get();
    3856            0 :             result.max_logical_size = std::cmp::max(
    3857            0 :                 result.max_logical_size,
    3858            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3859            0 :             );
    3860            0 :         }
    3861              : 
    3862            0 :         result.max_logical_size_per_shard = result
    3863            0 :             .max_logical_size
    3864            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    3865            0 : 
    3866            0 :         result
    3867            0 :     }
    3868              : }
    3869              : 
    3870              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3871              : /// perform a topological sort, so that the parent of each timeline comes
    3872              : /// before the children.
    3873              : /// E extracts the ancestor from T
    3874              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3875          452 : fn tree_sort_timelines<T, E>(
    3876          452 :     timelines: HashMap<TimelineId, T>,
    3877          452 :     extractor: E,
    3878          452 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3879          452 : where
    3880          452 :     E: Fn(&T) -> Option<TimelineId>,
    3881          452 : {
    3882          452 :     let mut result = Vec::with_capacity(timelines.len());
    3883          452 : 
    3884          452 :     let mut now = Vec::with_capacity(timelines.len());
    3885          452 :     // (ancestor, children)
    3886          452 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3887          452 :         HashMap::with_capacity(timelines.len());
    3888              : 
    3889          464 :     for (timeline_id, value) in timelines {
    3890           12 :         if let Some(ancestor_id) = extractor(&value) {
    3891            4 :             let children = later.entry(ancestor_id).or_default();
    3892            4 :             children.push((timeline_id, value));
    3893            8 :         } else {
    3894            8 :             now.push((timeline_id, value));
    3895            8 :         }
    3896              :     }
    3897              : 
    3898          464 :     while let Some((timeline_id, metadata)) = now.pop() {
    3899           12 :         result.push((timeline_id, metadata));
    3900              :         // All children of this can be loaded now
    3901           12 :         if let Some(mut children) = later.remove(&timeline_id) {
    3902            4 :             now.append(&mut children);
    3903            8 :         }
    3904              :     }
    3905              : 
    3906              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3907          452 :     if !later.is_empty() {
    3908            0 :         for (missing_id, orphan_ids) in later {
    3909            0 :             for (orphan_id, _) in orphan_ids {
    3910            0 :                 error!(
    3911            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    3912              :                 );
    3913              :             }
    3914              :         }
    3915            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3916          452 :     }
    3917          452 : 
    3918          452 :     Ok(result)
    3919          452 : }
    3920              : 
    3921              : enum ActivateTimelineArgs {
    3922              :     Yes {
    3923              :         broker_client: storage_broker::BrokerClientChannel,
    3924              :     },
    3925              :     No,
    3926              : }
    3927              : 
    3928              : impl Tenant {
    3929            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3930            0 :         self.tenant_conf.load().tenant_conf.clone()
    3931            0 :     }
    3932              : 
    3933            0 :     pub fn effective_config(&self) -> TenantConf {
    3934            0 :         self.tenant_specific_overrides()
    3935            0 :             .merge(self.conf.default_tenant_conf.clone())
    3936            0 :     }
    3937              : 
    3938            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3939            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3940            0 :         tenant_conf
    3941            0 :             .checkpoint_distance
    3942            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3943            0 :     }
    3944              : 
    3945            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3946            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3947            0 :         tenant_conf
    3948            0 :             .checkpoint_timeout
    3949            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3950            0 :     }
    3951              : 
    3952            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3953            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3954            0 :         tenant_conf
    3955            0 :             .compaction_target_size
    3956            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3957            0 :     }
    3958              : 
    3959            0 :     pub fn get_compaction_period(&self) -> Duration {
    3960            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3961            0 :         tenant_conf
    3962            0 :             .compaction_period
    3963            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3964            0 :     }
    3965              : 
    3966            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3967            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3968            0 :         tenant_conf
    3969            0 :             .compaction_threshold
    3970            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3971            0 :     }
    3972              : 
    3973            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    3974            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3975            0 :         tenant_conf
    3976            0 :             .rel_size_v2_enabled
    3977            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    3978            0 :     }
    3979              : 
    3980            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    3981            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3982            0 :         tenant_conf
    3983            0 :             .compaction_upper_limit
    3984            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    3985            0 :     }
    3986              : 
    3987            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    3988            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3989            0 :         tenant_conf
    3990            0 :             .compaction_l0_first
    3991            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    3992            0 :     }
    3993              : 
    3994            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3995            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3996            0 :         tenant_conf
    3997            0 :             .gc_horizon
    3998            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3999            0 :     }
    4000              : 
    4001            0 :     pub fn get_gc_period(&self) -> Duration {
    4002            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4003            0 :         tenant_conf
    4004            0 :             .gc_period
    4005            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4006            0 :     }
    4007              : 
    4008            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4009            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4010            0 :         tenant_conf
    4011            0 :             .image_creation_threshold
    4012            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4013            0 :     }
    4014              : 
    4015            0 :     pub fn get_pitr_interval(&self) -> Duration {
    4016            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4017            0 :         tenant_conf
    4018            0 :             .pitr_interval
    4019            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4020            0 :     }
    4021              : 
    4022            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4023            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4024            0 :         tenant_conf
    4025            0 :             .min_resident_size_override
    4026            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4027            0 :     }
    4028              : 
    4029            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4030            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4031            0 :         let heatmap_period = tenant_conf
    4032            0 :             .heatmap_period
    4033            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4034            0 :         if heatmap_period.is_zero() {
    4035            0 :             None
    4036              :         } else {
    4037            0 :             Some(heatmap_period)
    4038              :         }
    4039            0 :     }
    4040              : 
    4041            8 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4042            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4043            8 :         tenant_conf
    4044            8 :             .lsn_lease_length
    4045            8 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4046            8 :     }
    4047              : 
    4048            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4049            0 :         if self.conf.timeline_offloading {
    4050            0 :             return true;
    4051            0 :         }
    4052            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4053            0 :         tenant_conf
    4054            0 :             .timeline_offloading
    4055            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4056            0 :     }
    4057              : 
    4058              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4059            4 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4060            4 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    4061            4 : 
    4062            4 :         let mut timeline_manifests = timelines_offloaded
    4063            4 :             .iter()
    4064            4 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    4065            4 :             .collect::<Vec<_>>();
    4066            4 :         // Sort the manifests so that our output is deterministic
    4067            4 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    4068            4 : 
    4069            4 :         TenantManifest {
    4070            4 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4071            4 :             offloaded_timelines: timeline_manifests,
    4072            4 :         }
    4073            4 :     }
    4074              : 
    4075            0 :     pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
    4076            0 :         &self,
    4077            0 :         update: F,
    4078            0 :     ) -> anyhow::Result<TenantConfOpt> {
    4079            0 :         // Use read-copy-update in order to avoid overwriting the location config
    4080            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    4081            0 :         // this race is not possible if both request types come from the storage
    4082            0 :         // controller (as they should!) because an exclusive op lock is required
    4083            0 :         // on the storage controller side.
    4084            0 : 
    4085            0 :         self.tenant_conf
    4086            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4087            0 :                 Ok(Arc::new(AttachedTenantConf {
    4088            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4089            0 :                     location: attached_conf.location,
    4090            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4091              :                 }))
    4092            0 :             })?;
    4093              : 
    4094            0 :         let updated = self.tenant_conf.load();
    4095            0 : 
    4096            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    4097            0 :         // Don't hold self.timelines.lock() during the notifies.
    4098            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4099            0 :         // mutexes in struct Timeline in the future.
    4100            0 :         let timelines = self.list_timelines();
    4101            0 :         for timeline in timelines {
    4102            0 :             timeline.tenant_conf_updated(&updated);
    4103            0 :         }
    4104              : 
    4105            0 :         Ok(updated.tenant_conf.clone())
    4106            0 :     }
    4107              : 
    4108            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4109            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4110            0 : 
    4111            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4112            0 : 
    4113            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4114            0 :         // Don't hold self.timelines.lock() during the notifies.
    4115            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4116            0 :         // mutexes in struct Timeline in the future.
    4117            0 :         let timelines = self.list_timelines();
    4118            0 :         for timeline in timelines {
    4119            0 :             timeline.tenant_conf_updated(&new_conf);
    4120            0 :         }
    4121            0 :     }
    4122              : 
    4123          452 :     fn get_pagestream_throttle_config(
    4124          452 :         psconf: &'static PageServerConf,
    4125          452 :         overrides: &TenantConfOpt,
    4126          452 :     ) -> throttle::Config {
    4127          452 :         overrides
    4128          452 :             .timeline_get_throttle
    4129          452 :             .clone()
    4130          452 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4131          452 :     }
    4132              : 
    4133            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    4134            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4135            0 :         self.pagestream_throttle.reconfigure(conf)
    4136            0 :     }
    4137              : 
    4138              :     /// Helper function to create a new Timeline struct.
    4139              :     ///
    4140              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4141              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4142              :     /// map.
    4143              :     ///
    4144              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4145              :     /// and we might not have the ancestor present anymore which is fine for to be
    4146              :     /// deleted timelines.
    4147              :     #[allow(clippy::too_many_arguments)]
    4148          904 :     fn create_timeline_struct(
    4149          904 :         &self,
    4150          904 :         new_timeline_id: TimelineId,
    4151          904 :         new_metadata: &TimelineMetadata,
    4152          904 :         previous_heatmap: Option<PreviousHeatmap>,
    4153          904 :         ancestor: Option<Arc<Timeline>>,
    4154          904 :         resources: TimelineResources,
    4155          904 :         cause: CreateTimelineCause,
    4156          904 :         create_idempotency: CreateTimelineIdempotency,
    4157          904 :         gc_compaction_state: Option<GcCompactionState>,
    4158          904 :         rel_size_v2_status: Option<RelSizeMigration>,
    4159          904 :         ctx: &RequestContext,
    4160          904 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4161          904 :         let state = match cause {
    4162              :             CreateTimelineCause::Load => {
    4163          904 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4164          904 :                 anyhow::ensure!(
    4165          904 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4166            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4167              :                 );
    4168          904 :                 TimelineState::Loading
    4169              :             }
    4170            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4171              :         };
    4172              : 
    4173          904 :         let pg_version = new_metadata.pg_version();
    4174          904 : 
    4175          904 :         let timeline = Timeline::new(
    4176          904 :             self.conf,
    4177          904 :             Arc::clone(&self.tenant_conf),
    4178          904 :             new_metadata,
    4179          904 :             previous_heatmap,
    4180          904 :             ancestor,
    4181          904 :             new_timeline_id,
    4182          904 :             self.tenant_shard_id,
    4183          904 :             self.generation,
    4184          904 :             self.shard_identity,
    4185          904 :             self.walredo_mgr.clone(),
    4186          904 :             resources,
    4187          904 :             pg_version,
    4188          904 :             state,
    4189          904 :             self.attach_wal_lag_cooldown.clone(),
    4190          904 :             create_idempotency,
    4191          904 :             gc_compaction_state,
    4192          904 :             rel_size_v2_status,
    4193          904 :             self.cancel.child_token(),
    4194          904 :         );
    4195          904 : 
    4196          904 :         let timeline_ctx = RequestContextBuilder::extend(ctx)
    4197          904 :             .scope(context::Scope::new_timeline(&timeline))
    4198          904 :             .build();
    4199          904 : 
    4200          904 :         Ok((timeline, timeline_ctx))
    4201          904 :     }
    4202              : 
    4203              :     /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
    4204              :     /// to ensure proper cleanup of background tasks and metrics.
    4205              :     //
    4206              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4207              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4208              :     #[allow(clippy::too_many_arguments)]
    4209          452 :     fn new(
    4210          452 :         state: TenantState,
    4211          452 :         conf: &'static PageServerConf,
    4212          452 :         attached_conf: AttachedTenantConf,
    4213          452 :         shard_identity: ShardIdentity,
    4214          452 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4215          452 :         tenant_shard_id: TenantShardId,
    4216          452 :         remote_storage: GenericRemoteStorage,
    4217          452 :         deletion_queue_client: DeletionQueueClient,
    4218          452 :         l0_flush_global_state: L0FlushGlobalState,
    4219          452 :     ) -> Tenant {
    4220          452 :         debug_assert!(
    4221          452 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4222              :         );
    4223              : 
    4224          452 :         let (state, mut rx) = watch::channel(state);
    4225          452 : 
    4226          452 :         tokio::spawn(async move {
    4227          451 :             // reflect tenant state in metrics:
    4228          451 :             // - global per tenant state: TENANT_STATE_METRIC
    4229          451 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4230          451 :             //
    4231          451 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4232          451 :             // alerting.
    4233          451 : 
    4234          451 :             let tid = tenant_shard_id.to_string();
    4235          451 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4236          451 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4237              : 
    4238          903 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4239          903 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4240          903 :             }
    4241              : 
    4242          451 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4243          451 : 
    4244          451 :             let is_broken = tuple.1;
    4245          451 :             let mut counted_broken = if is_broken {
    4246              :                 // add the id to the set right away, there should not be any updates on the channel
    4247              :                 // after before tenant is removed, if ever
    4248            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4249            0 :                 true
    4250              :             } else {
    4251          451 :                 false
    4252              :             };
    4253              : 
    4254              :             loop {
    4255          903 :                 let labels = &tuple.0;
    4256          903 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4257          903 :                 current.inc();
    4258          903 : 
    4259          903 :                 if rx.changed().await.is_err() {
    4260              :                     // tenant has been dropped
    4261           28 :                     current.dec();
    4262           28 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4263           28 :                     break;
    4264          452 :                 }
    4265          452 : 
    4266          452 :                 current.dec();
    4267          452 :                 tuple = inspect_state(&rx.borrow_and_update());
    4268          452 : 
    4269          452 :                 let is_broken = tuple.1;
    4270          452 :                 if is_broken && !counted_broken {
    4271            0 :                     counted_broken = true;
    4272            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4273            0 :                     // access
    4274            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4275          452 :                 }
    4276              :             }
    4277          452 :         });
    4278          452 : 
    4279          452 :         Tenant {
    4280          452 :             tenant_shard_id,
    4281          452 :             shard_identity,
    4282          452 :             generation: attached_conf.location.generation,
    4283          452 :             conf,
    4284          452 :             // using now here is good enough approximation to catch tenants with really long
    4285          452 :             // activation times.
    4286          452 :             constructed_at: Instant::now(),
    4287          452 :             timelines: Mutex::new(HashMap::new()),
    4288          452 :             timelines_creating: Mutex::new(HashSet::new()),
    4289          452 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4290          452 :             tenant_manifest_upload: Default::default(),
    4291          452 :             gc_cs: tokio::sync::Mutex::new(()),
    4292          452 :             walredo_mgr,
    4293          452 :             remote_storage,
    4294          452 :             deletion_queue_client,
    4295          452 :             state,
    4296          452 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4297          452 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4298          452 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4299          452 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4300          452 :                 format!("compaction-{tenant_shard_id}"),
    4301          452 :                 5,
    4302          452 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4303          452 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4304          452 :                 // use an extremely long backoff.
    4305          452 :                 Some(Duration::from_secs(3600 * 24)),
    4306          452 :             )),
    4307          452 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4308          452 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4309          452 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4310          452 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4311          452 :             cancel: CancellationToken::default(),
    4312          452 :             gate: Gate::default(),
    4313          452 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4314          452 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4315          452 :             )),
    4316          452 :             pagestream_throttle_metrics: Arc::new(
    4317          452 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4318          452 :             ),
    4319          452 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4320          452 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4321          452 :             gc_block: Default::default(),
    4322          452 :             l0_flush_global_state,
    4323          452 :         }
    4324          452 :     }
    4325              : 
    4326              :     /// Locate and load config
    4327            0 :     pub(super) fn load_tenant_config(
    4328            0 :         conf: &'static PageServerConf,
    4329            0 :         tenant_shard_id: &TenantShardId,
    4330            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4331            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4332            0 : 
    4333            0 :         info!("loading tenant configuration from {config_path}");
    4334              : 
    4335              :         // load and parse file
    4336            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4337            0 :             match e.kind() {
    4338              :                 std::io::ErrorKind::NotFound => {
    4339              :                     // The config should almost always exist for a tenant directory:
    4340              :                     //  - When attaching a tenant, the config is the first thing we write
    4341              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4342              :                     //    before deleting contents.
    4343              :                     //
    4344              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4345              :                     // between creating directory and writing config.  Callers should handle that as if the
    4346              :                     // directory didn't exist.
    4347              : 
    4348            0 :                     LoadConfigError::NotFound(config_path)
    4349              :                 }
    4350              :                 _ => {
    4351              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4352              :                     // that we cannot cleanly recover
    4353            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4354              :                 }
    4355              :             }
    4356            0 :         })?;
    4357              : 
    4358            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4359            0 :     }
    4360              : 
    4361              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4362              :     pub(super) async fn persist_tenant_config(
    4363              :         conf: &'static PageServerConf,
    4364              :         tenant_shard_id: &TenantShardId,
    4365              :         location_conf: &LocationConf,
    4366              :     ) -> std::io::Result<()> {
    4367              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4368              : 
    4369              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4370              :     }
    4371              : 
    4372              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4373              :     pub(super) async fn persist_tenant_config_at(
    4374              :         tenant_shard_id: &TenantShardId,
    4375              :         config_path: &Utf8Path,
    4376              :         location_conf: &LocationConf,
    4377              :     ) -> std::io::Result<()> {
    4378              :         debug!("persisting tenantconf to {config_path}");
    4379              : 
    4380              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4381              : #  It is read in case of pageserver restart.
    4382              : "#
    4383              :         .to_string();
    4384              : 
    4385            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4386            0 :             Err(std::io::Error::new(
    4387            0 :                 std::io::ErrorKind::Other,
    4388            0 :                 "tenant-config-before-write",
    4389            0 :             ))
    4390            0 :         });
    4391              : 
    4392              :         // Convert the config to a toml file.
    4393              :         conf_content +=
    4394              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4395              : 
    4396              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4397              : 
    4398              :         let conf_content = conf_content.into_bytes();
    4399              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4400              :     }
    4401              : 
    4402              :     //
    4403              :     // How garbage collection works:
    4404              :     //
    4405              :     //                    +--bar------------->
    4406              :     //                   /
    4407              :     //             +----+-----foo---------------->
    4408              :     //            /
    4409              :     // ----main--+-------------------------->
    4410              :     //                \
    4411              :     //                 +-----baz-------->
    4412              :     //
    4413              :     //
    4414              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4415              :     //    `gc_infos` are being refreshed
    4416              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4417              :     //    all the points where other timelines have been branched off.
    4418              :     //    We will refrain from removing page versions at those LSNs.
    4419              :     // 3. For each timeline, scan all layer files on the timeline.
    4420              :     //    Remove all files for which a newer file exists and which
    4421              :     //    don't cover any branch point LSNs.
    4422              :     //
    4423              :     // TODO:
    4424              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4425              :     //   don't need to keep that in the parent anymore. But currently
    4426              :     //   we do.
    4427            8 :     async fn gc_iteration_internal(
    4428            8 :         &self,
    4429            8 :         target_timeline_id: Option<TimelineId>,
    4430            8 :         horizon: u64,
    4431            8 :         pitr: Duration,
    4432            8 :         cancel: &CancellationToken,
    4433            8 :         ctx: &RequestContext,
    4434            8 :     ) -> Result<GcResult, GcError> {
    4435            8 :         let mut totals: GcResult = Default::default();
    4436            8 :         let now = Instant::now();
    4437              : 
    4438            8 :         let gc_timelines = self
    4439            8 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4440            8 :             .await?;
    4441              : 
    4442            8 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4443              : 
    4444              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4445            8 :         if !gc_timelines.is_empty() {
    4446            8 :             info!("{} timelines need GC", gc_timelines.len());
    4447              :         } else {
    4448            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4449              :         }
    4450              : 
    4451              :         // Perform GC for each timeline.
    4452              :         //
    4453              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4454              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4455              :         // with branch creation.
    4456              :         //
    4457              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4458              :         // creation task can run concurrently with timeline's GC iteration.
    4459           16 :         for timeline in gc_timelines {
    4460            8 :             if cancel.is_cancelled() {
    4461              :                 // We were requested to shut down. Stop and return with the progress we
    4462              :                 // made.
    4463            0 :                 break;
    4464            8 :             }
    4465            8 :             let result = match timeline.gc().await {
    4466              :                 Err(GcError::TimelineCancelled) => {
    4467            0 :                     if target_timeline_id.is_some() {
    4468              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4469            0 :                         return Err(GcError::TimelineCancelled);
    4470              :                     } else {
    4471              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4472              :                         // skip past this and proceed to try GC on other timelines.
    4473            0 :                         continue;
    4474              :                     }
    4475              :                 }
    4476            8 :                 r => r?,
    4477              :             };
    4478            8 :             totals += result;
    4479              :         }
    4480              : 
    4481            8 :         totals.elapsed = now.elapsed();
    4482            8 :         Ok(totals)
    4483            8 :     }
    4484              : 
    4485              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4486              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4487              :     /// [`Tenant::get_gc_horizon`].
    4488              :     ///
    4489              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4490            0 :     pub(crate) async fn refresh_gc_info(
    4491            0 :         &self,
    4492            0 :         cancel: &CancellationToken,
    4493            0 :         ctx: &RequestContext,
    4494            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4495            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4496            0 :         // might be that these configuration values get applied faster than what it was previously,
    4497            0 :         // since these were only read from the gc task.
    4498            0 :         let horizon = self.get_gc_horizon();
    4499            0 :         let pitr = self.get_pitr_interval();
    4500            0 : 
    4501            0 :         // refresh all timelines
    4502            0 :         let target_timeline_id = None;
    4503            0 : 
    4504            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4505            0 :             .await
    4506            0 :     }
    4507              : 
    4508              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4509              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4510              :     ///
    4511              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4512            0 :     fn initialize_gc_info(
    4513            0 :         &self,
    4514            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4515            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4516            0 :         restrict_to_timeline: Option<TimelineId>,
    4517            0 :     ) {
    4518            0 :         if restrict_to_timeline.is_none() {
    4519              :             // This function must be called before activation: after activation timeline create/delete operations
    4520              :             // might happen, and this function is not safe to run concurrently with those.
    4521            0 :             assert!(!self.is_active());
    4522            0 :         }
    4523              : 
    4524              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4525              :         // the branch point where it was created.
    4526            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4527            0 :             BTreeMap::new();
    4528            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4529            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4530            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4531            0 :                 ancestor_children.push((
    4532            0 :                     timeline_entry.get_ancestor_lsn(),
    4533            0 :                     *timeline_id,
    4534            0 :                     MaybeOffloaded::No,
    4535            0 :                 ));
    4536            0 :             }
    4537            0 :         });
    4538            0 :         timelines_offloaded
    4539            0 :             .iter()
    4540            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4541            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4542            0 :                     return;
    4543              :                 };
    4544            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4545            0 :                     return;
    4546              :                 };
    4547            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4548            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4549            0 :             });
    4550            0 : 
    4551            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4552            0 :         let horizon = self.get_gc_horizon();
    4553              : 
    4554              :         // Populate each timeline's GcInfo with information about its child branches
    4555            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4556            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4557              :         } else {
    4558            0 :             itertools::Either::Right(timelines.values())
    4559              :         };
    4560            0 :         for timeline in timelines_to_write {
    4561            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4562            0 :                 .remove(&timeline.timeline_id)
    4563            0 :                 .unwrap_or_default();
    4564            0 : 
    4565            0 :             branchpoints.sort_by_key(|b| b.0);
    4566            0 : 
    4567            0 :             let mut target = timeline.gc_info.write().unwrap();
    4568            0 : 
    4569            0 :             target.retain_lsns = branchpoints;
    4570            0 : 
    4571            0 :             let space_cutoff = timeline
    4572            0 :                 .get_last_record_lsn()
    4573            0 :                 .checked_sub(horizon)
    4574            0 :                 .unwrap_or(Lsn(0));
    4575            0 : 
    4576            0 :             target.cutoffs = GcCutoffs {
    4577            0 :                 space: space_cutoff,
    4578            0 :                 time: Lsn::INVALID,
    4579            0 :             };
    4580            0 :         }
    4581            0 :     }
    4582              : 
    4583            8 :     async fn refresh_gc_info_internal(
    4584            8 :         &self,
    4585            8 :         target_timeline_id: Option<TimelineId>,
    4586            8 :         horizon: u64,
    4587            8 :         pitr: Duration,
    4588            8 :         cancel: &CancellationToken,
    4589            8 :         ctx: &RequestContext,
    4590            8 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4591            8 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4592            8 :         // currently visible timelines.
    4593            8 :         let timelines = self
    4594            8 :             .timelines
    4595            8 :             .lock()
    4596            8 :             .unwrap()
    4597            8 :             .values()
    4598            8 :             .filter(|tl| match target_timeline_id.as_ref() {
    4599            8 :                 Some(target) => &tl.timeline_id == target,
    4600            0 :                 None => true,
    4601            8 :             })
    4602            8 :             .cloned()
    4603            8 :             .collect::<Vec<_>>();
    4604            8 : 
    4605            8 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4606              :             // We were to act on a particular timeline and it wasn't found
    4607            0 :             return Err(GcError::TimelineNotFound);
    4608            8 :         }
    4609            8 : 
    4610            8 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4611            8 :             HashMap::with_capacity(timelines.len());
    4612            8 : 
    4613            8 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4614            8 :         let now_ts_for_pitr_calc = SystemTime::now();
    4615            8 :         for timeline in timelines.iter() {
    4616            8 :             let ctx = &ctx.with_scope_timeline(timeline);
    4617            8 :             let cutoff = timeline
    4618            8 :                 .get_last_record_lsn()
    4619            8 :                 .checked_sub(horizon)
    4620            8 :                 .unwrap_or(Lsn(0));
    4621              : 
    4622            8 :             let cutoffs = timeline
    4623            8 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4624            8 :                 .await?;
    4625            8 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4626            8 :             assert!(old.is_none());
    4627              :         }
    4628              : 
    4629            8 :         if !self.is_active() || self.cancel.is_cancelled() {
    4630            0 :             return Err(GcError::TenantCancelled);
    4631            8 :         }
    4632              : 
    4633              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4634              :         // because that will stall branch creation.
    4635            8 :         let gc_cs = self.gc_cs.lock().await;
    4636              : 
    4637              :         // Ok, we now know all the branch points.
    4638              :         // Update the GC information for each timeline.
    4639            8 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4640           16 :         for timeline in timelines {
    4641              :             // We filtered the timeline list above
    4642            8 :             if let Some(target_timeline_id) = target_timeline_id {
    4643            8 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4644            0 :             }
    4645              : 
    4646              :             {
    4647            8 :                 let mut target = timeline.gc_info.write().unwrap();
    4648            8 : 
    4649            8 :                 // Cull any expired leases
    4650            8 :                 let now = SystemTime::now();
    4651           12 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4652            8 : 
    4653            8 :                 timeline
    4654            8 :                     .metrics
    4655            8 :                     .valid_lsn_lease_count_gauge
    4656            8 :                     .set(target.leases.len() as u64);
    4657              : 
    4658              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4659            8 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4660            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4661            0 :                         target.within_ancestor_pitr =
    4662            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4663            0 :                     }
    4664            8 :                 }
    4665              : 
    4666              :                 // Update metrics that depend on GC state
    4667            8 :                 timeline
    4668            8 :                     .metrics
    4669            8 :                     .archival_size
    4670            8 :                     .set(if target.within_ancestor_pitr {
    4671            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4672              :                     } else {
    4673            8 :                         0
    4674              :                     });
    4675            8 :                 timeline.metrics.pitr_history_size.set(
    4676            8 :                     timeline
    4677            8 :                         .get_last_record_lsn()
    4678            8 :                         .checked_sub(target.cutoffs.time)
    4679            8 :                         .unwrap_or(Lsn(0))
    4680            8 :                         .0,
    4681            8 :                 );
    4682              : 
    4683              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4684              :                 // - this timeline was created while we were finding cutoffs
    4685              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4686            8 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4687            8 :                     let original_cutoffs = target.cutoffs.clone();
    4688            8 :                     // GC cutoffs should never go back
    4689            8 :                     target.cutoffs = GcCutoffs {
    4690            8 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4691            8 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4692            8 :                     }
    4693            0 :                 }
    4694              :             }
    4695              : 
    4696            8 :             gc_timelines.push(timeline);
    4697              :         }
    4698            8 :         drop(gc_cs);
    4699            8 :         Ok(gc_timelines)
    4700            8 :     }
    4701              : 
    4702              :     /// A substitute for `branch_timeline` for use in unit tests.
    4703              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4704              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4705              :     /// timeline background tasks are launched, except the flush loop.
    4706              :     #[cfg(test)]
    4707          464 :     async fn branch_timeline_test(
    4708          464 :         self: &Arc<Self>,
    4709          464 :         src_timeline: &Arc<Timeline>,
    4710          464 :         dst_id: TimelineId,
    4711          464 :         ancestor_lsn: Option<Lsn>,
    4712          464 :         ctx: &RequestContext,
    4713          464 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4714          464 :         let tl = self
    4715          464 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4716          464 :             .await?
    4717          456 :             .into_timeline_for_test();
    4718          456 :         tl.set_state(TimelineState::Active);
    4719          456 :         Ok(tl)
    4720          464 :     }
    4721              : 
    4722              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4723              :     #[cfg(test)]
    4724              :     #[allow(clippy::too_many_arguments)]
    4725           12 :     pub async fn branch_timeline_test_with_layers(
    4726           12 :         self: &Arc<Self>,
    4727           12 :         src_timeline: &Arc<Timeline>,
    4728           12 :         dst_id: TimelineId,
    4729           12 :         ancestor_lsn: Option<Lsn>,
    4730           12 :         ctx: &RequestContext,
    4731           12 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4732           12 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4733           12 :         end_lsn: Lsn,
    4734           12 :     ) -> anyhow::Result<Arc<Timeline>> {
    4735              :         use checks::check_valid_layermap;
    4736              :         use itertools::Itertools;
    4737              : 
    4738           12 :         let tline = self
    4739           12 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4740           12 :             .await?;
    4741           12 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4742           12 :             ancestor_lsn
    4743              :         } else {
    4744            0 :             tline.get_last_record_lsn()
    4745              :         };
    4746           12 :         assert!(end_lsn >= ancestor_lsn);
    4747           12 :         tline.force_advance_lsn(end_lsn);
    4748           24 :         for deltas in delta_layer_desc {
    4749           12 :             tline
    4750           12 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4751           12 :                 .await?;
    4752              :         }
    4753           20 :         for (lsn, images) in image_layer_desc {
    4754            8 :             tline
    4755            8 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4756            8 :                 .await?;
    4757              :         }
    4758           12 :         let layer_names = tline
    4759           12 :             .layers
    4760           12 :             .read()
    4761           12 :             .await
    4762           12 :             .layer_map()
    4763           12 :             .unwrap()
    4764           12 :             .iter_historic_layers()
    4765           20 :             .map(|layer| layer.layer_name())
    4766           12 :             .collect_vec();
    4767           12 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4768            0 :             bail!("invalid layermap: {err}");
    4769           12 :         }
    4770           12 :         Ok(tline)
    4771           12 :     }
    4772              : 
    4773              :     /// Branch an existing timeline.
    4774            0 :     async fn branch_timeline(
    4775            0 :         self: &Arc<Self>,
    4776            0 :         src_timeline: &Arc<Timeline>,
    4777            0 :         dst_id: TimelineId,
    4778            0 :         start_lsn: Option<Lsn>,
    4779            0 :         ctx: &RequestContext,
    4780            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4781            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4782            0 :             .await
    4783            0 :     }
    4784              : 
    4785          464 :     async fn branch_timeline_impl(
    4786          464 :         self: &Arc<Self>,
    4787          464 :         src_timeline: &Arc<Timeline>,
    4788          464 :         dst_id: TimelineId,
    4789          464 :         start_lsn: Option<Lsn>,
    4790          464 :         ctx: &RequestContext,
    4791          464 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4792          464 :         let src_id = src_timeline.timeline_id;
    4793              : 
    4794              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4795              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4796              :         // valid while we are creating the branch.
    4797          464 :         let _gc_cs = self.gc_cs.lock().await;
    4798              : 
    4799              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4800          464 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4801            4 :             let lsn = src_timeline.get_last_record_lsn();
    4802            4 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4803            4 :             lsn
    4804          464 :         });
    4805              : 
    4806              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4807          464 :         let timeline_create_guard = match self
    4808          464 :             .start_creating_timeline(
    4809          464 :                 dst_id,
    4810          464 :                 CreateTimelineIdempotency::Branch {
    4811          464 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4812          464 :                     ancestor_start_lsn: start_lsn,
    4813          464 :                 },
    4814          464 :             )
    4815          464 :             .await?
    4816              :         {
    4817          464 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4818            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4819            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4820              :             }
    4821              :         };
    4822              : 
    4823              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4824              :         // horizon on the source timeline
    4825              :         //
    4826              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4827              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4828              :         // planned GC cutoff in 'gc_info' is normally larger than
    4829              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    4830              :         // changed the GC settings for the tenant to make the PITR window
    4831              :         // larger, but some of the data was already removed by an earlier GC
    4832              :         // iteration.
    4833              : 
    4834              :         // check against last actual 'latest_gc_cutoff' first
    4835          464 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    4836          464 :         {
    4837          464 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4838          464 :             let planned_cutoff = gc_info.min_cutoff();
    4839          464 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    4840            0 :                 tracing::info!(
    4841            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    4842            0 :                     *applied_gc_cutoff_lsn
    4843              :                 );
    4844              :             } else {
    4845          464 :                 src_timeline
    4846          464 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    4847          464 :                     .context(format!(
    4848          464 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    4849          464 :                         *applied_gc_cutoff_lsn,
    4850          464 :                     ))
    4851          464 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    4852              : 
    4853              :                 // and then the planned GC cutoff
    4854          456 :                 if start_lsn < planned_cutoff {
    4855            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4856            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    4857            0 :                     )));
    4858          456 :                 }
    4859              :             }
    4860              :         }
    4861              : 
    4862              :         //
    4863              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4864              :         // so that GC cannot advance the GC cutoff until we are finished.
    4865              :         // Proceed with the branch creation.
    4866              :         //
    4867              : 
    4868              :         // Determine prev-LSN for the new timeline. We can only determine it if
    4869              :         // the timeline was branched at the current end of the source timeline.
    4870              :         let RecordLsn {
    4871          456 :             last: src_last,
    4872          456 :             prev: src_prev,
    4873          456 :         } = src_timeline.get_last_record_rlsn();
    4874          456 :         let dst_prev = if src_last == start_lsn {
    4875          432 :             Some(src_prev)
    4876              :         } else {
    4877           24 :             None
    4878              :         };
    4879              : 
    4880              :         // Create the metadata file, noting the ancestor of the new timeline.
    4881              :         // There is initially no data in it, but all the read-calls know to look
    4882              :         // into the ancestor.
    4883          456 :         let metadata = TimelineMetadata::new(
    4884          456 :             start_lsn,
    4885          456 :             dst_prev,
    4886          456 :             Some(src_id),
    4887          456 :             start_lsn,
    4888          456 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4889          456 :             src_timeline.initdb_lsn,
    4890          456 :             src_timeline.pg_version,
    4891          456 :         );
    4892              : 
    4893          456 :         let (uninitialized_timeline, _timeline_ctx) = self
    4894          456 :             .prepare_new_timeline(
    4895          456 :                 dst_id,
    4896          456 :                 &metadata,
    4897          456 :                 timeline_create_guard,
    4898          456 :                 start_lsn + 1,
    4899          456 :                 Some(Arc::clone(src_timeline)),
    4900          456 :                 Some(src_timeline.get_rel_size_v2_status()),
    4901          456 :                 ctx,
    4902          456 :             )
    4903          456 :             .await?;
    4904              : 
    4905          456 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    4906              : 
    4907              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4908              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4909              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4910              :         // could get incorrect information and remove more layers, than needed.
    4911              :         // See also https://github.com/neondatabase/neon/issues/3865
    4912          456 :         new_timeline
    4913          456 :             .remote_client
    4914          456 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4915          456 :             .context("branch initial metadata upload")?;
    4916              : 
    4917              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4918              : 
    4919          456 :         Ok(CreateTimelineResult::Created(new_timeline))
    4920          464 :     }
    4921              : 
    4922              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4923              :     #[cfg(test)]
    4924              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4925              :     pub(crate) async fn bootstrap_timeline_test(
    4926              :         self: &Arc<Self>,
    4927              :         timeline_id: TimelineId,
    4928              :         pg_version: u32,
    4929              :         load_existing_initdb: Option<TimelineId>,
    4930              :         ctx: &RequestContext,
    4931              :     ) -> anyhow::Result<Arc<Timeline>> {
    4932              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4933              :             .await
    4934              :             .map_err(anyhow::Error::new)
    4935            4 :             .map(|r| r.into_timeline_for_test())
    4936              :     }
    4937              : 
    4938              :     /// Get exclusive access to the timeline ID for creation.
    4939              :     ///
    4940              :     /// Timeline-creating code paths must use this function before making changes
    4941              :     /// to in-memory or persistent state.
    4942              :     ///
    4943              :     /// The `state` parameter is a description of the timeline creation operation
    4944              :     /// we intend to perform.
    4945              :     /// If the timeline was already created in the meantime, we check whether this
    4946              :     /// request conflicts or is idempotent , based on `state`.
    4947          904 :     async fn start_creating_timeline(
    4948          904 :         self: &Arc<Self>,
    4949          904 :         new_timeline_id: TimelineId,
    4950          904 :         idempotency: CreateTimelineIdempotency,
    4951          904 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4952          904 :         let allow_offloaded = false;
    4953          904 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4954          900 :             Ok(create_guard) => {
    4955          900 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4956          900 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4957              :             }
    4958            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4959              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4960              :                 // Creation is in progress, we cannot create it again, and we cannot
    4961              :                 // check if this request matches the existing one, so caller must try
    4962              :                 // again later.
    4963            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4964              :             }
    4965            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4966              :             Err(TimelineExclusionError::AlreadyExists {
    4967            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4968            0 :                 ..
    4969            0 :             }) => {
    4970            0 :                 info!("timeline already exists but is offloaded");
    4971            0 :                 Err(CreateTimelineError::Conflict)
    4972              :             }
    4973              :             Err(TimelineExclusionError::AlreadyExists {
    4974            4 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4975            4 :                 arg,
    4976            4 :             }) => {
    4977            4 :                 {
    4978            4 :                     let existing = &existing.create_idempotency;
    4979            4 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4980            4 :                     debug!("timeline already exists");
    4981              : 
    4982            4 :                     match (existing, &arg) {
    4983              :                         // FailWithConflict => no idempotency check
    4984              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4985              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4986            4 :                             warn!("timeline already exists, failing request");
    4987            4 :                             return Err(CreateTimelineError::Conflict);
    4988              :                         }
    4989              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4990            0 :                         (x, y) if x == y => {
    4991            0 :                             info!(
    4992            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    4993              :                             );
    4994              :                             // fallthrough
    4995              :                         }
    4996              :                         (_, _) => {
    4997            0 :                             warn!("idempotency conflict, failing request");
    4998            0 :                             return Err(CreateTimelineError::Conflict);
    4999              :                         }
    5000              :                     }
    5001              :                 }
    5002              : 
    5003            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5004              :             }
    5005              :         }
    5006          904 :     }
    5007              : 
    5008            0 :     async fn upload_initdb(
    5009            0 :         &self,
    5010            0 :         timelines_path: &Utf8PathBuf,
    5011            0 :         pgdata_path: &Utf8PathBuf,
    5012            0 :         timeline_id: &TimelineId,
    5013            0 :     ) -> anyhow::Result<()> {
    5014            0 :         let temp_path = timelines_path.join(format!(
    5015            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5016            0 :         ));
    5017            0 : 
    5018            0 :         scopeguard::defer! {
    5019            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    5020            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5021            0 :             }
    5022            0 :         }
    5023              : 
    5024            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5025              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5026            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5027            0 :             warn!(
    5028            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5029              :             );
    5030            0 :         }
    5031              : 
    5032            0 :         pausable_failpoint!("before-initdb-upload");
    5033              : 
    5034            0 :         backoff::retry(
    5035            0 :             || async {
    5036            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5037            0 :                     &self.remote_storage,
    5038            0 :                     &self.tenant_shard_id.tenant_id,
    5039            0 :                     timeline_id,
    5040            0 :                     pgdata_zstd.try_clone().await?,
    5041            0 :                     tar_zst_size,
    5042            0 :                     &self.cancel,
    5043            0 :                 )
    5044            0 :                 .await
    5045            0 :             },
    5046            0 :             |_| false,
    5047            0 :             3,
    5048            0 :             u32::MAX,
    5049            0 :             "persist_initdb_tar_zst",
    5050            0 :             &self.cancel,
    5051            0 :         )
    5052            0 :         .await
    5053            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5054            0 :         .and_then(|x| x)
    5055            0 :     }
    5056              : 
    5057              :     /// - run initdb to init temporary instance and get bootstrap data
    5058              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5059            4 :     async fn bootstrap_timeline(
    5060            4 :         self: &Arc<Self>,
    5061            4 :         timeline_id: TimelineId,
    5062            4 :         pg_version: u32,
    5063            4 :         load_existing_initdb: Option<TimelineId>,
    5064            4 :         ctx: &RequestContext,
    5065            4 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5066            4 :         let timeline_create_guard = match self
    5067            4 :             .start_creating_timeline(
    5068            4 :                 timeline_id,
    5069            4 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5070            4 :             )
    5071            4 :             .await?
    5072              :         {
    5073            4 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5074            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5075            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5076              :             }
    5077              :         };
    5078              : 
    5079              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5080              :         // temporary directory for basebackup files for the given timeline.
    5081              : 
    5082            4 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5083            4 :         let pgdata_path = path_with_suffix_extension(
    5084            4 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5085            4 :             TEMP_FILE_SUFFIX,
    5086            4 :         );
    5087            4 : 
    5088            4 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5089            4 :         // we won't race with other creations or existent timelines with the same path.
    5090            4 :         if pgdata_path.exists() {
    5091            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5092            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5093            0 :             })?;
    5094            4 :         }
    5095              : 
    5096              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5097            4 :         let pgdata_path_deferred = pgdata_path.clone();
    5098            4 :         scopeguard::defer! {
    5099            4 :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred) {
    5100            4 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5101            4 :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5102            4 :             }
    5103            4 :         }
    5104            4 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5105            4 :             if existing_initdb_timeline_id != timeline_id {
    5106            0 :                 let source_path = &remote_initdb_archive_path(
    5107            0 :                     &self.tenant_shard_id.tenant_id,
    5108            0 :                     &existing_initdb_timeline_id,
    5109            0 :                 );
    5110            0 :                 let dest_path =
    5111            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5112            0 : 
    5113            0 :                 // if this fails, it will get retried by retried control plane requests
    5114            0 :                 self.remote_storage
    5115            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5116            0 :                     .await
    5117            0 :                     .context("copy initdb tar")?;
    5118            4 :             }
    5119            4 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5120            4 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5121            4 :                     self.conf,
    5122            4 :                     &self.remote_storage,
    5123            4 :                     &self.tenant_shard_id,
    5124            4 :                     &existing_initdb_timeline_id,
    5125            4 :                     &self.cancel,
    5126            4 :                 )
    5127            4 :                 .await
    5128            4 :                 .context("download initdb tar")?;
    5129              : 
    5130            4 :             scopeguard::defer! {
    5131            4 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5132            4 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5133            4 :                 }
    5134            4 :             }
    5135            4 : 
    5136            4 :             let buf_read =
    5137            4 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5138            4 :             extract_zst_tarball(&pgdata_path, buf_read)
    5139            4 :                 .await
    5140            4 :                 .context("extract initdb tar")?;
    5141              :         } else {
    5142              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5143            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5144            0 :                 .await
    5145            0 :                 .context("run initdb")?;
    5146              : 
    5147              :             // Upload the created data dir to S3
    5148            0 :             if self.tenant_shard_id().is_shard_zero() {
    5149            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5150            0 :                     .await?;
    5151            0 :             }
    5152              :         }
    5153            4 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5154            4 : 
    5155            4 :         // Import the contents of the data directory at the initial checkpoint
    5156            4 :         // LSN, and any WAL after that.
    5157            4 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5158            4 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5159            4 :         let new_metadata = TimelineMetadata::new(
    5160            4 :             Lsn(0),
    5161            4 :             None,
    5162            4 :             None,
    5163            4 :             Lsn(0),
    5164            4 :             pgdata_lsn,
    5165            4 :             pgdata_lsn,
    5166            4 :             pg_version,
    5167            4 :         );
    5168            4 :         let (mut raw_timeline, timeline_ctx) = self
    5169            4 :             .prepare_new_timeline(
    5170            4 :                 timeline_id,
    5171            4 :                 &new_metadata,
    5172            4 :                 timeline_create_guard,
    5173            4 :                 pgdata_lsn,
    5174            4 :                 None,
    5175            4 :                 None,
    5176            4 :                 ctx,
    5177            4 :             )
    5178            4 :             .await?;
    5179              : 
    5180            4 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5181            4 :         raw_timeline
    5182            4 :             .write(|unfinished_timeline| async move {
    5183            4 :                 import_datadir::import_timeline_from_postgres_datadir(
    5184            4 :                     &unfinished_timeline,
    5185            4 :                     &pgdata_path,
    5186            4 :                     pgdata_lsn,
    5187            4 :                     &timeline_ctx,
    5188            4 :                 )
    5189            4 :                 .await
    5190            4 :                 .with_context(|| {
    5191            0 :                     format!(
    5192            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5193            0 :                     )
    5194            4 :                 })?;
    5195              : 
    5196            4 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5197            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5198            0 :                         "failpoint before-checkpoint-new-timeline"
    5199            0 :                     )))
    5200            4 :                 });
    5201              : 
    5202            4 :                 Ok(())
    5203            8 :             })
    5204            4 :             .await?;
    5205              : 
    5206              :         // All done!
    5207            4 :         let timeline = raw_timeline.finish_creation().await?;
    5208              : 
    5209              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5210              : 
    5211            4 :         Ok(CreateTimelineResult::Created(timeline))
    5212            4 :     }
    5213              : 
    5214          892 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5215          892 :         RemoteTimelineClient::new(
    5216          892 :             self.remote_storage.clone(),
    5217          892 :             self.deletion_queue_client.clone(),
    5218          892 :             self.conf,
    5219          892 :             self.tenant_shard_id,
    5220          892 :             timeline_id,
    5221          892 :             self.generation,
    5222          892 :             &self.tenant_conf.load().location,
    5223          892 :         )
    5224          892 :     }
    5225              : 
    5226              :     /// Builds required resources for a new timeline.
    5227          892 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5228          892 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5229          892 :         self.get_timeline_resources_for(remote_client)
    5230          892 :     }
    5231              : 
    5232              :     /// Builds timeline resources for the given remote client.
    5233          904 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5234          904 :         TimelineResources {
    5235          904 :             remote_client,
    5236          904 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5237          904 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5238          904 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5239          904 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5240          904 :         }
    5241          904 :     }
    5242              : 
    5243              :     /// Creates intermediate timeline structure and its files.
    5244              :     ///
    5245              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5246              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5247              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5248              :     #[allow(clippy::too_many_arguments)]
    5249          892 :     async fn prepare_new_timeline<'a>(
    5250          892 :         &'a self,
    5251          892 :         new_timeline_id: TimelineId,
    5252          892 :         new_metadata: &TimelineMetadata,
    5253          892 :         create_guard: TimelineCreateGuard,
    5254          892 :         start_lsn: Lsn,
    5255          892 :         ancestor: Option<Arc<Timeline>>,
    5256          892 :         rel_size_v2_status: Option<RelSizeMigration>,
    5257          892 :         ctx: &RequestContext,
    5258          892 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5259          892 :         let tenant_shard_id = self.tenant_shard_id;
    5260          892 : 
    5261          892 :         let resources = self.build_timeline_resources(new_timeline_id);
    5262          892 :         resources
    5263          892 :             .remote_client
    5264          892 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5265              : 
    5266          892 :         let (timeline_struct, timeline_ctx) = self
    5267          892 :             .create_timeline_struct(
    5268          892 :                 new_timeline_id,
    5269          892 :                 new_metadata,
    5270          892 :                 None,
    5271          892 :                 ancestor,
    5272          892 :                 resources,
    5273          892 :                 CreateTimelineCause::Load,
    5274          892 :                 create_guard.idempotency.clone(),
    5275          892 :                 None,
    5276          892 :                 rel_size_v2_status,
    5277          892 :                 ctx,
    5278          892 :             )
    5279          892 :             .context("Failed to create timeline data structure")?;
    5280              : 
    5281          892 :         timeline_struct.init_empty_layer_map(start_lsn);
    5282              : 
    5283          892 :         if let Err(e) = self
    5284          892 :             .create_timeline_files(&create_guard.timeline_path)
    5285          892 :             .await
    5286              :         {
    5287            0 :             error!(
    5288            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5289              :             );
    5290            0 :             cleanup_timeline_directory(create_guard);
    5291            0 :             return Err(e);
    5292          892 :         }
    5293          892 : 
    5294          892 :         debug!(
    5295            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5296              :         );
    5297              : 
    5298          892 :         Ok((
    5299          892 :             UninitializedTimeline::new(
    5300          892 :                 self,
    5301          892 :                 new_timeline_id,
    5302          892 :                 Some((timeline_struct, create_guard)),
    5303          892 :             ),
    5304          892 :             timeline_ctx,
    5305          892 :         ))
    5306          892 :     }
    5307              : 
    5308          892 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5309          892 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5310              : 
    5311          892 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5312            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5313          892 :         });
    5314              : 
    5315          892 :         Ok(())
    5316          892 :     }
    5317              : 
    5318              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5319              :     /// concurrent attempts to create the same timeline.
    5320              :     ///
    5321              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5322              :     /// offloaded timelines or not.
    5323          904 :     fn create_timeline_create_guard(
    5324          904 :         self: &Arc<Self>,
    5325          904 :         timeline_id: TimelineId,
    5326          904 :         idempotency: CreateTimelineIdempotency,
    5327          904 :         allow_offloaded: bool,
    5328          904 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5329          904 :         let tenant_shard_id = self.tenant_shard_id;
    5330          904 : 
    5331          904 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5332              : 
    5333          904 :         let create_guard = TimelineCreateGuard::new(
    5334          904 :             self,
    5335          904 :             timeline_id,
    5336          904 :             timeline_path.clone(),
    5337          904 :             idempotency,
    5338          904 :             allow_offloaded,
    5339          904 :         )?;
    5340              : 
    5341              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5342              :         // for creation.
    5343              :         // A timeline directory should never exist on disk already:
    5344              :         // - a previous failed creation would have cleaned up after itself
    5345              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5346              :         //
    5347              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5348              :         // this error may indicate a bug in cleanup on failed creations.
    5349          900 :         if timeline_path.exists() {
    5350            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5351            0 :                 "Timeline directory already exists! This is a bug."
    5352            0 :             )));
    5353          900 :         }
    5354          900 : 
    5355          900 :         Ok(create_guard)
    5356          904 :     }
    5357              : 
    5358              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5359              :     ///
    5360              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5361              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5362              :     pub async fn gather_size_inputs(
    5363              :         &self,
    5364              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5365              :         // (only if it is shorter than the real cutoff).
    5366              :         max_retention_period: Option<u64>,
    5367              :         cause: LogicalSizeCalculationCause,
    5368              :         cancel: &CancellationToken,
    5369              :         ctx: &RequestContext,
    5370              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5371              :         let logical_sizes_at_once = self
    5372              :             .conf
    5373              :             .concurrent_tenant_size_logical_size_queries
    5374              :             .inner();
    5375              : 
    5376              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5377              :         //
    5378              :         // But the only case where we need to run multiple of these at once is when we
    5379              :         // request a size for a tenant manually via API, while another background calculation
    5380              :         // is in progress (which is not a common case).
    5381              :         //
    5382              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5383              :         let mut shared_cache = tokio::select! {
    5384              :             locked = self.cached_logical_sizes.lock() => locked,
    5385              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5386              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5387              :         };
    5388              : 
    5389              :         size::gather_inputs(
    5390              :             self,
    5391              :             logical_sizes_at_once,
    5392              :             max_retention_period,
    5393              :             &mut shared_cache,
    5394              :             cause,
    5395              :             cancel,
    5396              :             ctx,
    5397              :         )
    5398              :         .await
    5399              :     }
    5400              : 
    5401              :     /// Calculate synthetic tenant size and cache the result.
    5402              :     /// This is periodically called by background worker.
    5403              :     /// result is cached in tenant struct
    5404              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5405              :     pub async fn calculate_synthetic_size(
    5406              :         &self,
    5407              :         cause: LogicalSizeCalculationCause,
    5408              :         cancel: &CancellationToken,
    5409              :         ctx: &RequestContext,
    5410              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5411              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5412              : 
    5413              :         let size = inputs.calculate();
    5414              : 
    5415              :         self.set_cached_synthetic_size(size);
    5416              : 
    5417              :         Ok(size)
    5418              :     }
    5419              : 
    5420              :     /// Cache given synthetic size and update the metric value
    5421            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5422            0 :         self.cached_synthetic_tenant_size
    5423            0 :             .store(size, Ordering::Relaxed);
    5424            0 : 
    5425            0 :         // Only shard zero should be calculating synthetic sizes
    5426            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5427              : 
    5428            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5429            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5430            0 :             .unwrap()
    5431            0 :             .set(size);
    5432            0 :     }
    5433              : 
    5434            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5435            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5436            0 :     }
    5437              : 
    5438              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5439              :     ///
    5440              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5441              :     /// from an external API handler.
    5442              :     ///
    5443              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5444              :     /// still bounded by tenant/timeline shutdown.
    5445              :     #[tracing::instrument(skip_all)]
    5446              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5447              :         let timelines = self.timelines.lock().unwrap().clone();
    5448              : 
    5449            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5450            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5451            0 :             timeline.freeze_and_flush().await?;
    5452            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5453            0 :             timeline.remote_client.wait_completion().await?;
    5454              : 
    5455            0 :             Ok(())
    5456            0 :         }
    5457              : 
    5458              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5459              :         // aborted when this function's future is cancelled: they should stay alive
    5460              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5461              :         // before Timeline shutdown completes.
    5462              :         let mut results = FuturesUnordered::new();
    5463              : 
    5464              :         for (_timeline_id, timeline) in timelines {
    5465              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5466              :             // means that if this function's future is cancelled, the Timeline shutdown
    5467              :             // will still wait for any I/O in here to complete.
    5468              :             let Ok(gate) = timeline.gate.enter() else {
    5469              :                 continue;
    5470              :             };
    5471            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5472              :             results.push(jh);
    5473              :         }
    5474              : 
    5475              :         while let Some(r) = results.next().await {
    5476              :             if let Err(e) = r {
    5477              :                 if !e.is_cancelled() && !e.is_panic() {
    5478              :                     tracing::error!("unexpected join error: {e:?}");
    5479              :                 }
    5480              :             }
    5481              :         }
    5482              : 
    5483              :         // The flushes we did above were just writes, but the Tenant might have had
    5484              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5485              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5486              :         // because it's typically a no-op.
    5487              :         match self.deletion_queue_client.flush_execute().await {
    5488              :             Ok(_) => {}
    5489              :             Err(DeletionQueueError::ShuttingDown) => {}
    5490              :         }
    5491              : 
    5492              :         Ok(())
    5493              :     }
    5494              : 
    5495            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5496            0 :         self.tenant_conf.load().tenant_conf.clone()
    5497            0 :     }
    5498              : 
    5499              :     /// How much local storage would this tenant like to have?  It can cope with
    5500              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5501              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5502              :     /// by keeping important things on local disk.
    5503              :     ///
    5504              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5505              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5506              :     /// actually use more than they report here.
    5507            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5508            0 :         let timelines = self.timelines.lock().unwrap();
    5509            0 : 
    5510            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5511            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5512            0 :         // of them is used actively enough to occupy space on disk.
    5513            0 :         timelines
    5514            0 :             .values()
    5515            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5516            0 :             .max()
    5517            0 :             .unwrap_or(0)
    5518            0 :     }
    5519              : 
    5520              :     /// Serialize and write the latest TenantManifest to remote storage.
    5521            4 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5522              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5523              :         // must be loaded while holding this lock. This makes it safe to call this function
    5524              :         // from anywhere without worrying about colliding updates.
    5525            4 :         let mut guard = tokio::select! {
    5526            4 :             g = self.tenant_manifest_upload.lock() => {
    5527            4 :                 g
    5528              :             },
    5529            4 :             _ = self.cancel.cancelled() => {
    5530            0 :                 return Err(TenantManifestError::Cancelled);
    5531              :             }
    5532              :         };
    5533              : 
    5534            4 :         let manifest = self.build_tenant_manifest();
    5535            4 :         if Some(&manifest) == (*guard).as_ref() {
    5536              :             // Optimisation: skip uploads that don't change anything.
    5537            0 :             return Ok(());
    5538            4 :         }
    5539            4 : 
    5540            4 :         // Remote storage does no retries internally, so wrap it
    5541            4 :         match backoff::retry(
    5542            4 :             || async {
    5543            4 :                 upload_tenant_manifest(
    5544            4 :                     &self.remote_storage,
    5545            4 :                     &self.tenant_shard_id,
    5546            4 :                     self.generation,
    5547            4 :                     &manifest,
    5548            4 :                     &self.cancel,
    5549            4 :                 )
    5550            4 :                 .await
    5551            8 :             },
    5552            4 :             |_e| self.cancel.is_cancelled(),
    5553            4 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5554            4 :             FAILED_REMOTE_OP_RETRIES,
    5555            4 :             "uploading tenant manifest",
    5556            4 :             &self.cancel,
    5557            4 :         )
    5558            4 :         .await
    5559              :         {
    5560            0 :             None => Err(TenantManifestError::Cancelled),
    5561            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5562            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5563              :             Some(Ok(_)) => {
    5564              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5565              :                 // re-uploading the same thing.
    5566            4 :                 *guard = Some(manifest);
    5567            4 : 
    5568            4 :                 Ok(())
    5569              :             }
    5570              :         }
    5571            4 :     }
    5572              : }
    5573              : 
    5574              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5575              : /// to get bootstrap data for timeline initialization.
    5576            0 : async fn run_initdb(
    5577            0 :     conf: &'static PageServerConf,
    5578            0 :     initdb_target_dir: &Utf8Path,
    5579            0 :     pg_version: u32,
    5580            0 :     cancel: &CancellationToken,
    5581            0 : ) -> Result<(), InitdbError> {
    5582            0 :     let initdb_bin_path = conf
    5583            0 :         .pg_bin_dir(pg_version)
    5584            0 :         .map_err(InitdbError::Other)?
    5585            0 :         .join("initdb");
    5586            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5587            0 :     info!(
    5588            0 :         "running {} in {}, libdir: {}",
    5589              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5590              :     );
    5591              : 
    5592            0 :     let _permit = {
    5593            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5594            0 :         INIT_DB_SEMAPHORE.acquire().await
    5595              :     };
    5596              : 
    5597            0 :     CONCURRENT_INITDBS.inc();
    5598            0 :     scopeguard::defer! {
    5599            0 :         CONCURRENT_INITDBS.dec();
    5600            0 :     }
    5601            0 : 
    5602            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5603            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5604            0 :         superuser: &conf.superuser,
    5605            0 :         locale: &conf.locale,
    5606            0 :         initdb_bin: &initdb_bin_path,
    5607            0 :         pg_version,
    5608            0 :         library_search_path: &initdb_lib_dir,
    5609            0 :         pgdata: initdb_target_dir,
    5610            0 :     })
    5611            0 :     .await
    5612            0 :     .map_err(InitdbError::Inner);
    5613            0 : 
    5614            0 :     // This isn't true cancellation support, see above. Still return an error to
    5615            0 :     // excercise the cancellation code path.
    5616            0 :     if cancel.is_cancelled() {
    5617            0 :         return Err(InitdbError::Cancelled);
    5618            0 :     }
    5619            0 : 
    5620            0 :     res
    5621            0 : }
    5622              : 
    5623              : /// Dump contents of a layer file to stdout.
    5624            0 : pub async fn dump_layerfile_from_path(
    5625            0 :     path: &Utf8Path,
    5626            0 :     verbose: bool,
    5627            0 :     ctx: &RequestContext,
    5628            0 : ) -> anyhow::Result<()> {
    5629              :     use std::os::unix::fs::FileExt;
    5630              : 
    5631              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5632              :     // file.
    5633            0 :     let file = File::open(path)?;
    5634            0 :     let mut header_buf = [0u8; 2];
    5635            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5636              : 
    5637            0 :     match u16::from_be_bytes(header_buf) {
    5638              :         crate::IMAGE_FILE_MAGIC => {
    5639            0 :             ImageLayer::new_for_path(path, file)?
    5640            0 :                 .dump(verbose, ctx)
    5641            0 :                 .await?
    5642              :         }
    5643              :         crate::DELTA_FILE_MAGIC => {
    5644            0 :             DeltaLayer::new_for_path(path, file)?
    5645            0 :                 .dump(verbose, ctx)
    5646            0 :                 .await?
    5647              :         }
    5648            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5649              :     }
    5650              : 
    5651            0 :     Ok(())
    5652            0 : }
    5653              : 
    5654              : #[cfg(test)]
    5655              : pub(crate) mod harness {
    5656              :     use bytes::{Bytes, BytesMut};
    5657              :     use hex_literal::hex;
    5658              :     use once_cell::sync::OnceCell;
    5659              :     use pageserver_api::key::Key;
    5660              :     use pageserver_api::models::ShardParameters;
    5661              :     use pageserver_api::record::NeonWalRecord;
    5662              :     use pageserver_api::shard::ShardIndex;
    5663              :     use utils::id::TenantId;
    5664              :     use utils::logging;
    5665              : 
    5666              :     use super::*;
    5667              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5668              :     use crate::l0_flush::L0FlushConfig;
    5669              :     use crate::walredo::apply_neon;
    5670              : 
    5671              :     pub const TIMELINE_ID: TimelineId =
    5672              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5673              :     pub const NEW_TIMELINE_ID: TimelineId =
    5674              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5675              : 
    5676              :     /// Convenience function to create a page image with given string as the only content
    5677     10057462 :     pub fn test_img(s: &str) -> Bytes {
    5678     10057462 :         let mut buf = BytesMut::new();
    5679     10057462 :         buf.extend_from_slice(s.as_bytes());
    5680     10057462 :         buf.resize(64, 0);
    5681     10057462 : 
    5682     10057462 :         buf.freeze()
    5683     10057462 :     }
    5684              : 
    5685              :     impl From<TenantConf> for TenantConfOpt {
    5686          452 :         fn from(tenant_conf: TenantConf) -> Self {
    5687          452 :             Self {
    5688          452 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5689          452 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5690          452 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5691          452 :                 compaction_period: Some(tenant_conf.compaction_period),
    5692          452 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5693          452 :                 compaction_upper_limit: Some(tenant_conf.compaction_upper_limit),
    5694          452 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5695          452 :                 compaction_l0_first: Some(tenant_conf.compaction_l0_first),
    5696          452 :                 compaction_l0_semaphore: Some(tenant_conf.compaction_l0_semaphore),
    5697          452 :                 l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
    5698          452 :                 l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
    5699          452 :                 l0_flush_wait_upload: Some(tenant_conf.l0_flush_wait_upload),
    5700          452 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5701          452 :                 gc_period: Some(tenant_conf.gc_period),
    5702          452 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5703          452 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5704          452 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5705          452 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5706          452 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5707          452 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5708          452 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5709          452 :                 evictions_low_residence_duration_metric_threshold: Some(
    5710          452 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5711          452 :                 ),
    5712          452 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5713          452 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5714          452 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5715          452 :                 image_layer_creation_check_threshold: Some(
    5716          452 :                     tenant_conf.image_layer_creation_check_threshold,
    5717          452 :                 ),
    5718          452 :                 image_creation_preempt_threshold: Some(
    5719          452 :                     tenant_conf.image_creation_preempt_threshold,
    5720          452 :                 ),
    5721          452 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5722          452 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5723          452 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5724          452 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5725          452 :                 rel_size_v2_enabled: Some(tenant_conf.rel_size_v2_enabled),
    5726          452 :                 gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
    5727          452 :                 gc_compaction_initial_threshold_kb: Some(
    5728          452 :                     tenant_conf.gc_compaction_initial_threshold_kb,
    5729          452 :                 ),
    5730          452 :                 gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
    5731          452 :             }
    5732          452 :         }
    5733              :     }
    5734              : 
    5735              :     pub struct TenantHarness {
    5736              :         pub conf: &'static PageServerConf,
    5737              :         pub tenant_conf: TenantConf,
    5738              :         pub tenant_shard_id: TenantShardId,
    5739              :         pub generation: Generation,
    5740              :         pub shard: ShardIndex,
    5741              :         pub remote_storage: GenericRemoteStorage,
    5742              :         pub remote_fs_dir: Utf8PathBuf,
    5743              :         pub deletion_queue: MockDeletionQueue,
    5744              :     }
    5745              : 
    5746              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5747              : 
    5748          500 :     pub(crate) fn setup_logging() {
    5749          500 :         LOG_HANDLE.get_or_init(|| {
    5750          476 :             logging::init(
    5751          476 :                 logging::LogFormat::Test,
    5752          476 :                 // enable it in case the tests exercise code paths that use
    5753          476 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5754          476 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5755          476 :                 logging::Output::Stdout,
    5756          476 :             )
    5757          476 :             .expect("Failed to init test logging")
    5758          500 :         });
    5759          500 :     }
    5760              : 
    5761              :     impl TenantHarness {
    5762          452 :         pub async fn create_custom(
    5763          452 :             test_name: &'static str,
    5764          452 :             tenant_conf: TenantConf,
    5765          452 :             tenant_id: TenantId,
    5766          452 :             shard_identity: ShardIdentity,
    5767          452 :             generation: Generation,
    5768          452 :         ) -> anyhow::Result<Self> {
    5769          452 :             setup_logging();
    5770          452 : 
    5771          452 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5772          452 :             let _ = fs::remove_dir_all(&repo_dir);
    5773          452 :             fs::create_dir_all(&repo_dir)?;
    5774              : 
    5775          452 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5776          452 :             // Make a static copy of the config. This can never be free'd, but that's
    5777          452 :             // OK in a test.
    5778          452 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5779          452 : 
    5780          452 :             let shard = shard_identity.shard_index();
    5781          452 :             let tenant_shard_id = TenantShardId {
    5782          452 :                 tenant_id,
    5783          452 :                 shard_number: shard.shard_number,
    5784          452 :                 shard_count: shard.shard_count,
    5785          452 :             };
    5786          452 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5787          452 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5788              : 
    5789              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5790          452 :             let remote_fs_dir = conf.workdir.join("localfs");
    5791          452 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5792          452 :             let config = RemoteStorageConfig {
    5793          452 :                 storage: RemoteStorageKind::LocalFs {
    5794          452 :                     local_path: remote_fs_dir.clone(),
    5795          452 :                 },
    5796          452 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5797          452 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5798          452 :             };
    5799          452 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5800          452 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5801          452 : 
    5802          452 :             Ok(Self {
    5803          452 :                 conf,
    5804          452 :                 tenant_conf,
    5805          452 :                 tenant_shard_id,
    5806          452 :                 generation,
    5807          452 :                 shard,
    5808          452 :                 remote_storage,
    5809          452 :                 remote_fs_dir,
    5810          452 :                 deletion_queue,
    5811          452 :             })
    5812          452 :         }
    5813              : 
    5814          428 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5815          428 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5816          428 :             // The tests perform them manually if needed.
    5817          428 :             let tenant_conf = TenantConf {
    5818          428 :                 gc_period: Duration::ZERO,
    5819          428 :                 compaction_period: Duration::ZERO,
    5820          428 :                 ..TenantConf::default()
    5821          428 :             };
    5822          428 :             let tenant_id = TenantId::generate();
    5823          428 :             let shard = ShardIdentity::unsharded();
    5824          428 :             Self::create_custom(
    5825          428 :                 test_name,
    5826          428 :                 tenant_conf,
    5827          428 :                 tenant_id,
    5828          428 :                 shard,
    5829          428 :                 Generation::new(0xdeadbeef),
    5830          428 :             )
    5831          428 :             .await
    5832          428 :         }
    5833              : 
    5834           40 :         pub fn span(&self) -> tracing::Span {
    5835           40 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5836           40 :         }
    5837              : 
    5838          452 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5839          452 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    5840          452 :                 .with_scope_unit_test();
    5841          452 :             (
    5842          452 :                 self.do_try_load(&ctx)
    5843          452 :                     .await
    5844          452 :                     .expect("failed to load test tenant"),
    5845          452 :                 ctx,
    5846          452 :             )
    5847          452 :         }
    5848              : 
    5849              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5850              :         pub(crate) async fn do_try_load(
    5851              :             &self,
    5852              :             ctx: &RequestContext,
    5853              :         ) -> anyhow::Result<Arc<Tenant>> {
    5854              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5855              : 
    5856              :             let tenant = Arc::new(Tenant::new(
    5857              :                 TenantState::Attaching,
    5858              :                 self.conf,
    5859              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5860              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5861              :                     self.generation,
    5862              :                     &ShardParameters::default(),
    5863              :                 ))
    5864              :                 .unwrap(),
    5865              :                 // This is a legacy/test code path: sharding isn't supported here.
    5866              :                 ShardIdentity::unsharded(),
    5867              :                 Some(walredo_mgr),
    5868              :                 self.tenant_shard_id,
    5869              :                 self.remote_storage.clone(),
    5870              :                 self.deletion_queue.new_client(),
    5871              :                 // TODO: ideally we should run all unit tests with both configs
    5872              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5873              :             ));
    5874              : 
    5875              :             let preload = tenant
    5876              :                 .preload(&self.remote_storage, CancellationToken::new())
    5877              :                 .await?;
    5878              :             tenant.attach(Some(preload), ctx).await?;
    5879              : 
    5880              :             tenant.state.send_replace(TenantState::Active);
    5881              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5882              :                 timeline.set_state(TimelineState::Active);
    5883              :             }
    5884              :             Ok(tenant)
    5885              :         }
    5886              : 
    5887            4 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5888            4 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5889            4 :         }
    5890              :     }
    5891              : 
    5892              :     // Mock WAL redo manager that doesn't do much
    5893              :     pub(crate) struct TestRedoManager;
    5894              : 
    5895              :     impl TestRedoManager {
    5896              :         /// # Cancel-Safety
    5897              :         ///
    5898              :         /// This method is cancellation-safe.
    5899         1676 :         pub async fn request_redo(
    5900         1676 :             &self,
    5901         1676 :             key: Key,
    5902         1676 :             lsn: Lsn,
    5903         1676 :             base_img: Option<(Lsn, Bytes)>,
    5904         1676 :             records: Vec<(Lsn, NeonWalRecord)>,
    5905         1676 :             _pg_version: u32,
    5906         1676 :         ) -> Result<Bytes, walredo::Error> {
    5907         2472 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5908         1676 :             if records_neon {
    5909              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5910         1676 :                 let mut page = match (base_img, records.first()) {
    5911         1536 :                     (Some((_lsn, img)), _) => {
    5912         1536 :                         let mut page = BytesMut::new();
    5913         1536 :                         page.extend_from_slice(&img);
    5914         1536 :                         page
    5915              :                     }
    5916          140 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5917              :                     _ => {
    5918            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5919              :                     }
    5920              :                 };
    5921              : 
    5922         4148 :                 for (record_lsn, record) in records {
    5923         2472 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5924              :                 }
    5925         1676 :                 Ok(page.freeze())
    5926              :             } else {
    5927              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5928            0 :                 let s = format!(
    5929            0 :                     "redo for {} to get to {}, with {} and {} records",
    5930            0 :                     key,
    5931            0 :                     lsn,
    5932            0 :                     if base_img.is_some() {
    5933            0 :                         "base image"
    5934              :                     } else {
    5935            0 :                         "no base image"
    5936              :                     },
    5937            0 :                     records.len()
    5938            0 :                 );
    5939            0 :                 println!("{s}");
    5940            0 : 
    5941            0 :                 Ok(test_img(&s))
    5942              :             }
    5943         1676 :         }
    5944              :     }
    5945              : }
    5946              : 
    5947              : #[cfg(test)]
    5948              : mod tests {
    5949              :     use std::collections::{BTreeMap, BTreeSet};
    5950              : 
    5951              :     use bytes::{Bytes, BytesMut};
    5952              :     use hex_literal::hex;
    5953              :     use itertools::Itertools;
    5954              :     #[cfg(feature = "testing")]
    5955              :     use models::CompactLsnRange;
    5956              :     use pageserver_api::key::{AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
    5957              :     use pageserver_api::keyspace::KeySpace;
    5958              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5959              :     #[cfg(feature = "testing")]
    5960              :     use pageserver_api::record::NeonWalRecord;
    5961              :     use pageserver_api::value::Value;
    5962              :     use pageserver_compaction::helpers::overlaps_with;
    5963              :     use rand::{Rng, thread_rng};
    5964              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5965              :     use tests::storage_layer::ValuesReconstructState;
    5966              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5967              :     #[cfg(feature = "testing")]
    5968              :     use timeline::GcInfo;
    5969              :     #[cfg(feature = "testing")]
    5970              :     use timeline::InMemoryLayerTestDesc;
    5971              :     #[cfg(feature = "testing")]
    5972              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5973              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5974              :     use utils::id::TenantId;
    5975              : 
    5976              :     use super::*;
    5977              :     use crate::DEFAULT_PG_VERSION;
    5978              :     use crate::keyspace::KeySpaceAccum;
    5979              :     use crate::tenant::harness::*;
    5980              :     use crate::tenant::timeline::CompactFlags;
    5981              : 
    5982              :     static TEST_KEY: Lazy<Key> =
    5983           36 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5984              : 
    5985              :     #[tokio::test]
    5986            4 :     async fn test_basic() -> anyhow::Result<()> {
    5987            4 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5988            4 :         let tline = tenant
    5989            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5990            4 :             .await?;
    5991            4 : 
    5992            4 :         let mut writer = tline.writer().await;
    5993            4 :         writer
    5994            4 :             .put(
    5995            4 :                 *TEST_KEY,
    5996            4 :                 Lsn(0x10),
    5997            4 :                 &Value::Image(test_img("foo at 0x10")),
    5998            4 :                 &ctx,
    5999            4 :             )
    6000            4 :             .await?;
    6001            4 :         writer.finish_write(Lsn(0x10));
    6002            4 :         drop(writer);
    6003            4 : 
    6004            4 :         let mut writer = tline.writer().await;
    6005            4 :         writer
    6006            4 :             .put(
    6007            4 :                 *TEST_KEY,
    6008            4 :                 Lsn(0x20),
    6009            4 :                 &Value::Image(test_img("foo at 0x20")),
    6010            4 :                 &ctx,
    6011            4 :             )
    6012            4 :             .await?;
    6013            4 :         writer.finish_write(Lsn(0x20));
    6014            4 :         drop(writer);
    6015            4 : 
    6016            4 :         assert_eq!(
    6017            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6018            4 :             test_img("foo at 0x10")
    6019            4 :         );
    6020            4 :         assert_eq!(
    6021            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6022            4 :             test_img("foo at 0x10")
    6023            4 :         );
    6024            4 :         assert_eq!(
    6025            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6026            4 :             test_img("foo at 0x20")
    6027            4 :         );
    6028            4 : 
    6029            4 :         Ok(())
    6030            4 :     }
    6031              : 
    6032              :     #[tokio::test]
    6033            4 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6034            4 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6035            4 :             .await?
    6036            4 :             .load()
    6037            4 :             .await;
    6038            4 :         let _ = tenant
    6039            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6040            4 :             .await?;
    6041            4 : 
    6042            4 :         match tenant
    6043            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6044            4 :             .await
    6045            4 :         {
    6046            4 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6047            4 :             Err(e) => assert_eq!(
    6048            4 :                 e.to_string(),
    6049            4 :                 "timeline already exists with different parameters".to_string()
    6050            4 :             ),
    6051            4 :         }
    6052            4 : 
    6053            4 :         Ok(())
    6054            4 :     }
    6055              : 
    6056              :     /// Convenience function to create a page image with given string as the only content
    6057           20 :     pub fn test_value(s: &str) -> Value {
    6058           20 :         let mut buf = BytesMut::new();
    6059           20 :         buf.extend_from_slice(s.as_bytes());
    6060           20 :         Value::Image(buf.freeze())
    6061           20 :     }
    6062              : 
    6063              :     ///
    6064              :     /// Test branch creation
    6065              :     ///
    6066              :     #[tokio::test]
    6067            4 :     async fn test_branch() -> anyhow::Result<()> {
    6068            4 :         use std::str::from_utf8;
    6069            4 : 
    6070            4 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6071            4 :         let tline = tenant
    6072            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6073            4 :             .await?;
    6074            4 :         let mut writer = tline.writer().await;
    6075            4 : 
    6076            4 :         #[allow(non_snake_case)]
    6077            4 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6078            4 :         #[allow(non_snake_case)]
    6079            4 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6080            4 : 
    6081            4 :         // Insert a value on the timeline
    6082            4 :         writer
    6083            4 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6084            4 :             .await?;
    6085            4 :         writer
    6086            4 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6087            4 :             .await?;
    6088            4 :         writer.finish_write(Lsn(0x20));
    6089            4 : 
    6090            4 :         writer
    6091            4 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6092            4 :             .await?;
    6093            4 :         writer.finish_write(Lsn(0x30));
    6094            4 :         writer
    6095            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6096            4 :             .await?;
    6097            4 :         writer.finish_write(Lsn(0x40));
    6098            4 : 
    6099            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6100            4 : 
    6101            4 :         // Branch the history, modify relation differently on the new timeline
    6102            4 :         tenant
    6103            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6104            4 :             .await?;
    6105            4 :         let newtline = tenant
    6106            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6107            4 :             .expect("Should have a local timeline");
    6108            4 :         let mut new_writer = newtline.writer().await;
    6109            4 :         new_writer
    6110            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6111            4 :             .await?;
    6112            4 :         new_writer.finish_write(Lsn(0x40));
    6113            4 : 
    6114            4 :         // Check page contents on both branches
    6115            4 :         assert_eq!(
    6116            4 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6117            4 :             "foo at 0x40"
    6118            4 :         );
    6119            4 :         assert_eq!(
    6120            4 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6121            4 :             "bar at 0x40"
    6122            4 :         );
    6123            4 :         assert_eq!(
    6124            4 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6125            4 :             "foobar at 0x20"
    6126            4 :         );
    6127            4 : 
    6128            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6129            4 : 
    6130            4 :         Ok(())
    6131            4 :     }
    6132              : 
    6133           40 :     async fn make_some_layers(
    6134           40 :         tline: &Timeline,
    6135           40 :         start_lsn: Lsn,
    6136           40 :         ctx: &RequestContext,
    6137           40 :     ) -> anyhow::Result<()> {
    6138           40 :         let mut lsn = start_lsn;
    6139              :         {
    6140           40 :             let mut writer = tline.writer().await;
    6141              :             // Create a relation on the timeline
    6142           40 :             writer
    6143           40 :                 .put(
    6144           40 :                     *TEST_KEY,
    6145           40 :                     lsn,
    6146           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6147           40 :                     ctx,
    6148           40 :                 )
    6149           40 :                 .await?;
    6150           40 :             writer.finish_write(lsn);
    6151           40 :             lsn += 0x10;
    6152           40 :             writer
    6153           40 :                 .put(
    6154           40 :                     *TEST_KEY,
    6155           40 :                     lsn,
    6156           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6157           40 :                     ctx,
    6158           40 :                 )
    6159           40 :                 .await?;
    6160           40 :             writer.finish_write(lsn);
    6161           40 :             lsn += 0x10;
    6162           40 :         }
    6163           40 :         tline.freeze_and_flush().await?;
    6164              :         {
    6165           40 :             let mut writer = tline.writer().await;
    6166           40 :             writer
    6167           40 :                 .put(
    6168           40 :                     *TEST_KEY,
    6169           40 :                     lsn,
    6170           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6171           40 :                     ctx,
    6172           40 :                 )
    6173           40 :                 .await?;
    6174           40 :             writer.finish_write(lsn);
    6175           40 :             lsn += 0x10;
    6176           40 :             writer
    6177           40 :                 .put(
    6178           40 :                     *TEST_KEY,
    6179           40 :                     lsn,
    6180           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6181           40 :                     ctx,
    6182           40 :                 )
    6183           40 :                 .await?;
    6184           40 :             writer.finish_write(lsn);
    6185           40 :         }
    6186           40 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6187           40 :     }
    6188              : 
    6189              :     #[tokio::test(start_paused = true)]
    6190            4 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6191            4 :         let (tenant, ctx) =
    6192            4 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6193            4 :                 .await?
    6194            4 :                 .load()
    6195            4 :                 .await;
    6196            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6197            4 :         // initial transition into AttachedSingle.
    6198            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6199            4 :         tokio::time::resume();
    6200            4 :         let tline = tenant
    6201            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6202            4 :             .await?;
    6203            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6204            4 : 
    6205            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6206            4 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6207            4 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6208            4 :         // below should fail.
    6209            4 :         tenant
    6210            4 :             .gc_iteration(
    6211            4 :                 Some(TIMELINE_ID),
    6212            4 :                 0x10,
    6213            4 :                 Duration::ZERO,
    6214            4 :                 &CancellationToken::new(),
    6215            4 :                 &ctx,
    6216            4 :             )
    6217            4 :             .await?;
    6218            4 : 
    6219            4 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6220            4 :         match tenant
    6221            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6222            4 :             .await
    6223            4 :         {
    6224            4 :             Ok(_) => panic!("branching should have failed"),
    6225            4 :             Err(err) => {
    6226            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6227            4 :                     panic!("wrong error type")
    6228            4 :                 };
    6229            4 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6230            4 :                 assert!(
    6231            4 :                     err.source()
    6232            4 :                         .unwrap()
    6233            4 :                         .to_string()
    6234            4 :                         .contains("we might've already garbage collected needed data")
    6235            4 :                 )
    6236            4 :             }
    6237            4 :         }
    6238            4 : 
    6239            4 :         Ok(())
    6240            4 :     }
    6241              : 
    6242              :     #[tokio::test]
    6243            4 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6244            4 :         let (tenant, ctx) =
    6245            4 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6246            4 :                 .await?
    6247            4 :                 .load()
    6248            4 :                 .await;
    6249            4 : 
    6250            4 :         let tline = tenant
    6251            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6252            4 :             .await?;
    6253            4 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6254            4 :         match tenant
    6255            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6256            4 :             .await
    6257            4 :         {
    6258            4 :             Ok(_) => panic!("branching should have failed"),
    6259            4 :             Err(err) => {
    6260            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6261            4 :                     panic!("wrong error type");
    6262            4 :                 };
    6263            4 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6264            4 :                 assert!(
    6265            4 :                     &err.source()
    6266            4 :                         .unwrap()
    6267            4 :                         .to_string()
    6268            4 :                         .contains("is earlier than latest GC cutoff")
    6269            4 :                 );
    6270            4 :             }
    6271            4 :         }
    6272            4 : 
    6273            4 :         Ok(())
    6274            4 :     }
    6275              : 
    6276              :     /*
    6277              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6278              :     // remove the old value, we'd need to work a little harder
    6279              :     #[tokio::test]
    6280              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6281              :         let repo =
    6282              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6283              :             .load();
    6284              : 
    6285              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6286              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6287              : 
    6288              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6289              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6290              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6291              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6292              :             Ok(_) => panic!("request for page should have failed"),
    6293              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6294              :         }
    6295              :         Ok(())
    6296              :     }
    6297              :      */
    6298              : 
    6299              :     #[tokio::test]
    6300            4 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6301            4 :         let (tenant, ctx) =
    6302            4 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6303            4 :                 .await?
    6304            4 :                 .load()
    6305            4 :                 .await;
    6306            4 :         let tline = tenant
    6307            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6308            4 :             .await?;
    6309            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6310            4 : 
    6311            4 :         tenant
    6312            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6313            4 :             .await?;
    6314            4 :         let newtline = tenant
    6315            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6316            4 :             .expect("Should have a local timeline");
    6317            4 : 
    6318            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6319            4 : 
    6320            4 :         tline.set_broken("test".to_owned());
    6321            4 : 
    6322            4 :         tenant
    6323            4 :             .gc_iteration(
    6324            4 :                 Some(TIMELINE_ID),
    6325            4 :                 0x10,
    6326            4 :                 Duration::ZERO,
    6327            4 :                 &CancellationToken::new(),
    6328            4 :                 &ctx,
    6329            4 :             )
    6330            4 :             .await?;
    6331            4 : 
    6332            4 :         // The branchpoints should contain all timelines, even ones marked
    6333            4 :         // as Broken.
    6334            4 :         {
    6335            4 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6336            4 :             assert_eq!(branchpoints.len(), 1);
    6337            4 :             assert_eq!(
    6338            4 :                 branchpoints[0],
    6339            4 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6340            4 :             );
    6341            4 :         }
    6342            4 : 
    6343            4 :         // You can read the key from the child branch even though the parent is
    6344            4 :         // Broken, as long as you don't need to access data from the parent.
    6345            4 :         assert_eq!(
    6346            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6347            4 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6348            4 :         );
    6349            4 : 
    6350            4 :         // This needs to traverse to the parent, and fails.
    6351            4 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6352            4 :         assert!(
    6353            4 :             err.to_string().starts_with(&format!(
    6354            4 :                 "bad state on timeline {}: Broken",
    6355            4 :                 tline.timeline_id
    6356            4 :             )),
    6357            4 :             "{err}"
    6358            4 :         );
    6359            4 : 
    6360            4 :         Ok(())
    6361            4 :     }
    6362              : 
    6363              :     #[tokio::test]
    6364            4 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6365            4 :         let (tenant, ctx) =
    6366            4 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6367            4 :                 .await?
    6368            4 :                 .load()
    6369            4 :                 .await;
    6370            4 :         let tline = tenant
    6371            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6372            4 :             .await?;
    6373            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6374            4 : 
    6375            4 :         tenant
    6376            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6377            4 :             .await?;
    6378            4 :         let newtline = tenant
    6379            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6380            4 :             .expect("Should have a local timeline");
    6381            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6382            4 :         tenant
    6383            4 :             .gc_iteration(
    6384            4 :                 Some(TIMELINE_ID),
    6385            4 :                 0x10,
    6386            4 :                 Duration::ZERO,
    6387            4 :                 &CancellationToken::new(),
    6388            4 :                 &ctx,
    6389            4 :             )
    6390            4 :             .await?;
    6391            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6392            4 : 
    6393            4 :         Ok(())
    6394            4 :     }
    6395              :     #[tokio::test]
    6396            4 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6397            4 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6398            4 :             .await?
    6399            4 :             .load()
    6400            4 :             .await;
    6401            4 :         let tline = tenant
    6402            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6403            4 :             .await?;
    6404            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6405            4 : 
    6406            4 :         tenant
    6407            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6408            4 :             .await?;
    6409            4 :         let newtline = tenant
    6410            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6411            4 :             .expect("Should have a local timeline");
    6412            4 : 
    6413            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6414            4 : 
    6415            4 :         // run gc on parent
    6416            4 :         tenant
    6417            4 :             .gc_iteration(
    6418            4 :                 Some(TIMELINE_ID),
    6419            4 :                 0x10,
    6420            4 :                 Duration::ZERO,
    6421            4 :                 &CancellationToken::new(),
    6422            4 :                 &ctx,
    6423            4 :             )
    6424            4 :             .await?;
    6425            4 : 
    6426            4 :         // Check that the data is still accessible on the branch.
    6427            4 :         assert_eq!(
    6428            4 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6429            4 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6430            4 :         );
    6431            4 : 
    6432            4 :         Ok(())
    6433            4 :     }
    6434              : 
    6435              :     #[tokio::test]
    6436            4 :     async fn timeline_load() -> anyhow::Result<()> {
    6437            4 :         const TEST_NAME: &str = "timeline_load";
    6438            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6439            4 :         {
    6440            4 :             let (tenant, ctx) = harness.load().await;
    6441            4 :             let tline = tenant
    6442            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6443            4 :                 .await?;
    6444            4 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6445            4 :             // so that all uploads finish & we can call harness.load() below again
    6446            4 :             tenant
    6447            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6448            4 :                 .instrument(harness.span())
    6449            4 :                 .await
    6450            4 :                 .ok()
    6451            4 :                 .unwrap();
    6452            4 :         }
    6453            4 : 
    6454            4 :         let (tenant, _ctx) = harness.load().await;
    6455            4 :         tenant
    6456            4 :             .get_timeline(TIMELINE_ID, true)
    6457            4 :             .expect("cannot load timeline");
    6458            4 : 
    6459            4 :         Ok(())
    6460            4 :     }
    6461              : 
    6462              :     #[tokio::test]
    6463            4 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6464            4 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6465            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6466            4 :         // create two timelines
    6467            4 :         {
    6468            4 :             let (tenant, ctx) = harness.load().await;
    6469            4 :             let tline = tenant
    6470            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6471            4 :                 .await?;
    6472            4 : 
    6473            4 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6474            4 : 
    6475            4 :             let child_tline = tenant
    6476            4 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6477            4 :                 .await?;
    6478            4 :             child_tline.set_state(TimelineState::Active);
    6479            4 : 
    6480            4 :             let newtline = tenant
    6481            4 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6482            4 :                 .expect("Should have a local timeline");
    6483            4 : 
    6484            4 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6485            4 : 
    6486            4 :             // so that all uploads finish & we can call harness.load() below again
    6487            4 :             tenant
    6488            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6489            4 :                 .instrument(harness.span())
    6490            4 :                 .await
    6491            4 :                 .ok()
    6492            4 :                 .unwrap();
    6493            4 :         }
    6494            4 : 
    6495            4 :         // check that both of them are initially unloaded
    6496            4 :         let (tenant, _ctx) = harness.load().await;
    6497            4 : 
    6498            4 :         // check that both, child and ancestor are loaded
    6499            4 :         let _child_tline = tenant
    6500            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6501            4 :             .expect("cannot get child timeline loaded");
    6502            4 : 
    6503            4 :         let _ancestor_tline = tenant
    6504            4 :             .get_timeline(TIMELINE_ID, true)
    6505            4 :             .expect("cannot get ancestor timeline loaded");
    6506            4 : 
    6507            4 :         Ok(())
    6508            4 :     }
    6509              : 
    6510              :     #[tokio::test]
    6511            4 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6512            4 :         use storage_layer::AsLayerDesc;
    6513            4 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6514            4 :             .await?
    6515            4 :             .load()
    6516            4 :             .await;
    6517            4 :         let tline = tenant
    6518            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6519            4 :             .await?;
    6520            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6521            4 : 
    6522            4 :         let layer_map = tline.layers.read().await;
    6523            4 :         let level0_deltas = layer_map
    6524            4 :             .layer_map()?
    6525            4 :             .level0_deltas()
    6526            4 :             .iter()
    6527            8 :             .map(|desc| layer_map.get_from_desc(desc))
    6528            4 :             .collect::<Vec<_>>();
    6529            4 : 
    6530            4 :         assert!(!level0_deltas.is_empty());
    6531            4 : 
    6532           12 :         for delta in level0_deltas {
    6533            4 :             // Ensure we are dumping a delta layer here
    6534            8 :             assert!(delta.layer_desc().is_delta);
    6535            8 :             delta.dump(true, &ctx).await.unwrap();
    6536            4 :         }
    6537            4 : 
    6538            4 :         Ok(())
    6539            4 :     }
    6540              : 
    6541              :     #[tokio::test]
    6542            4 :     async fn test_images() -> anyhow::Result<()> {
    6543            4 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6544            4 :         let tline = tenant
    6545            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6546            4 :             .await?;
    6547            4 : 
    6548            4 :         let mut writer = tline.writer().await;
    6549            4 :         writer
    6550            4 :             .put(
    6551            4 :                 *TEST_KEY,
    6552            4 :                 Lsn(0x10),
    6553            4 :                 &Value::Image(test_img("foo at 0x10")),
    6554            4 :                 &ctx,
    6555            4 :             )
    6556            4 :             .await?;
    6557            4 :         writer.finish_write(Lsn(0x10));
    6558            4 :         drop(writer);
    6559            4 : 
    6560            4 :         tline.freeze_and_flush().await?;
    6561            4 :         tline
    6562            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6563            4 :             .await?;
    6564            4 : 
    6565            4 :         let mut writer = tline.writer().await;
    6566            4 :         writer
    6567            4 :             .put(
    6568            4 :                 *TEST_KEY,
    6569            4 :                 Lsn(0x20),
    6570            4 :                 &Value::Image(test_img("foo at 0x20")),
    6571            4 :                 &ctx,
    6572            4 :             )
    6573            4 :             .await?;
    6574            4 :         writer.finish_write(Lsn(0x20));
    6575            4 :         drop(writer);
    6576            4 : 
    6577            4 :         tline.freeze_and_flush().await?;
    6578            4 :         tline
    6579            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6580            4 :             .await?;
    6581            4 : 
    6582            4 :         let mut writer = tline.writer().await;
    6583            4 :         writer
    6584            4 :             .put(
    6585            4 :                 *TEST_KEY,
    6586            4 :                 Lsn(0x30),
    6587            4 :                 &Value::Image(test_img("foo at 0x30")),
    6588            4 :                 &ctx,
    6589            4 :             )
    6590            4 :             .await?;
    6591            4 :         writer.finish_write(Lsn(0x30));
    6592            4 :         drop(writer);
    6593            4 : 
    6594            4 :         tline.freeze_and_flush().await?;
    6595            4 :         tline
    6596            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6597            4 :             .await?;
    6598            4 : 
    6599            4 :         let mut writer = tline.writer().await;
    6600            4 :         writer
    6601            4 :             .put(
    6602            4 :                 *TEST_KEY,
    6603            4 :                 Lsn(0x40),
    6604            4 :                 &Value::Image(test_img("foo at 0x40")),
    6605            4 :                 &ctx,
    6606            4 :             )
    6607            4 :             .await?;
    6608            4 :         writer.finish_write(Lsn(0x40));
    6609            4 :         drop(writer);
    6610            4 : 
    6611            4 :         tline.freeze_and_flush().await?;
    6612            4 :         tline
    6613            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6614            4 :             .await?;
    6615            4 : 
    6616            4 :         assert_eq!(
    6617            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6618            4 :             test_img("foo at 0x10")
    6619            4 :         );
    6620            4 :         assert_eq!(
    6621            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6622            4 :             test_img("foo at 0x10")
    6623            4 :         );
    6624            4 :         assert_eq!(
    6625            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6626            4 :             test_img("foo at 0x20")
    6627            4 :         );
    6628            4 :         assert_eq!(
    6629            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6630            4 :             test_img("foo at 0x30")
    6631            4 :         );
    6632            4 :         assert_eq!(
    6633            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6634            4 :             test_img("foo at 0x40")
    6635            4 :         );
    6636            4 : 
    6637            4 :         Ok(())
    6638            4 :     }
    6639              : 
    6640            8 :     async fn bulk_insert_compact_gc(
    6641            8 :         tenant: &Tenant,
    6642            8 :         timeline: &Arc<Timeline>,
    6643            8 :         ctx: &RequestContext,
    6644            8 :         lsn: Lsn,
    6645            8 :         repeat: usize,
    6646            8 :         key_count: usize,
    6647            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6648            8 :         let compact = true;
    6649            8 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6650            8 :     }
    6651              : 
    6652           16 :     async fn bulk_insert_maybe_compact_gc(
    6653           16 :         tenant: &Tenant,
    6654           16 :         timeline: &Arc<Timeline>,
    6655           16 :         ctx: &RequestContext,
    6656           16 :         mut lsn: Lsn,
    6657           16 :         repeat: usize,
    6658           16 :         key_count: usize,
    6659           16 :         compact: bool,
    6660           16 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6661           16 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6662           16 : 
    6663           16 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6664           16 :         let mut blknum = 0;
    6665           16 : 
    6666           16 :         // Enforce that key range is monotonously increasing
    6667           16 :         let mut keyspace = KeySpaceAccum::new();
    6668           16 : 
    6669           16 :         let cancel = CancellationToken::new();
    6670           16 : 
    6671           16 :         for _ in 0..repeat {
    6672          800 :             for _ in 0..key_count {
    6673      8000000 :                 test_key.field6 = blknum;
    6674      8000000 :                 let mut writer = timeline.writer().await;
    6675      8000000 :                 writer
    6676      8000000 :                     .put(
    6677      8000000 :                         test_key,
    6678      8000000 :                         lsn,
    6679      8000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6680      8000000 :                         ctx,
    6681      8000000 :                     )
    6682      8000000 :                     .await?;
    6683      8000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6684      8000000 :                 writer.finish_write(lsn);
    6685      8000000 :                 drop(writer);
    6686      8000000 : 
    6687      8000000 :                 keyspace.add_key(test_key);
    6688      8000000 : 
    6689      8000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6690      8000000 :                 blknum += 1;
    6691              :             }
    6692              : 
    6693          800 :             timeline.freeze_and_flush().await?;
    6694          800 :             if compact {
    6695              :                 // this requires timeline to be &Arc<Timeline>
    6696          400 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6697          400 :             }
    6698              : 
    6699              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6700              :             // originally was.
    6701          800 :             let res = tenant
    6702          800 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6703          800 :                 .await?;
    6704              : 
    6705          800 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6706              :         }
    6707              : 
    6708           16 :         Ok(inserted)
    6709           16 :     }
    6710              : 
    6711              :     //
    6712              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6713              :     // Repeat 50 times.
    6714              :     //
    6715              :     #[tokio::test]
    6716            4 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6717            4 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6718            4 :         let (tenant, ctx) = harness.load().await;
    6719            4 :         let tline = tenant
    6720            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6721            4 :             .await?;
    6722            4 : 
    6723            4 :         let lsn = Lsn(0x10);
    6724            4 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6725            4 : 
    6726            4 :         Ok(())
    6727            4 :     }
    6728              : 
    6729              :     // Test the vectored get real implementation against a simple sequential implementation.
    6730              :     //
    6731              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6732              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6733              :     // grow to the right on the X axis.
    6734              :     //                       [Delta]
    6735              :     //                 [Delta]
    6736              :     //           [Delta]
    6737              :     //    [Delta]
    6738              :     // ------------ Image ---------------
    6739              :     //
    6740              :     // After layer generation we pick the ranges to query as follows:
    6741              :     // 1. The beginning of each delta layer
    6742              :     // 2. At the seam between two adjacent delta layers
    6743              :     //
    6744              :     // There's one major downside to this test: delta layers only contains images,
    6745              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6746              :     #[tokio::test]
    6747            4 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6748            4 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6749            4 :         let (tenant, ctx) = harness.load().await;
    6750            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6751            4 :         let tline = tenant
    6752            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6753            4 :             .await?;
    6754            4 : 
    6755            4 :         let lsn = Lsn(0x10);
    6756            4 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6757            4 : 
    6758            4 :         let guard = tline.layers.read().await;
    6759            4 :         let lm = guard.layer_map()?;
    6760            4 : 
    6761            4 :         lm.dump(true, &ctx).await?;
    6762            4 : 
    6763            4 :         let mut reads = Vec::new();
    6764            4 :         let mut prev = None;
    6765           24 :         lm.iter_historic_layers().for_each(|desc| {
    6766           24 :             if !desc.is_delta() {
    6767            4 :                 prev = Some(desc.clone());
    6768            4 :                 return;
    6769           20 :             }
    6770           20 : 
    6771           20 :             let start = desc.key_range.start;
    6772           20 :             let end = desc
    6773           20 :                 .key_range
    6774           20 :                 .start
    6775           20 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6776           20 :             reads.push(KeySpace {
    6777           20 :                 ranges: vec![start..end],
    6778           20 :             });
    6779            4 : 
    6780           20 :             if let Some(prev) = &prev {
    6781           20 :                 if !prev.is_delta() {
    6782           20 :                     return;
    6783            4 :                 }
    6784            0 : 
    6785            0 :                 let first_range = Key {
    6786            0 :                     field6: prev.key_range.end.field6 - 4,
    6787            0 :                     ..prev.key_range.end
    6788            0 :                 }..prev.key_range.end;
    6789            0 : 
    6790            0 :                 let second_range = desc.key_range.start..Key {
    6791            0 :                     field6: desc.key_range.start.field6 + 4,
    6792            0 :                     ..desc.key_range.start
    6793            0 :                 };
    6794            0 : 
    6795            0 :                 reads.push(KeySpace {
    6796            0 :                     ranges: vec![first_range, second_range],
    6797            0 :                 });
    6798            4 :             };
    6799            4 : 
    6800            4 :             prev = Some(desc.clone());
    6801           24 :         });
    6802            4 : 
    6803            4 :         drop(guard);
    6804            4 : 
    6805            4 :         // Pick a big LSN such that we query over all the changes.
    6806            4 :         let reads_lsn = Lsn(u64::MAX - 1);
    6807            4 : 
    6808           24 :         for read in reads {
    6809           20 :             info!("Doing vectored read on {:?}", read);
    6810            4 : 
    6811           20 :             let vectored_res = tline
    6812           20 :                 .get_vectored_impl(
    6813           20 :                     read.clone(),
    6814           20 :                     reads_lsn,
    6815           20 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    6816           20 :                     &ctx,
    6817           20 :                 )
    6818           20 :                 .await;
    6819            4 : 
    6820           20 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6821           20 :             let mut expect_missing = false;
    6822           20 :             let mut key = read.start().unwrap();
    6823          660 :             while key != read.end().unwrap() {
    6824          640 :                 if let Some(lsns) = inserted.get(&key) {
    6825          640 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6826          640 :                     match expected_lsn {
    6827          640 :                         Some(lsn) => {
    6828          640 :                             expected_lsns.insert(key, *lsn);
    6829          640 :                         }
    6830            4 :                         None => {
    6831            4 :                             expect_missing = true;
    6832            0 :                             break;
    6833            4 :                         }
    6834            4 :                     }
    6835            4 :                 } else {
    6836            4 :                     expect_missing = true;
    6837            0 :                     break;
    6838            4 :                 }
    6839            4 : 
    6840          640 :                 key = key.next();
    6841            4 :             }
    6842            4 : 
    6843           20 :             if expect_missing {
    6844            4 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6845            4 :             } else {
    6846          640 :                 for (key, image) in vectored_res? {
    6847          640 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6848          640 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6849          640 :                     assert_eq!(image?, expected_image);
    6850            4 :                 }
    6851            4 :             }
    6852            4 :         }
    6853            4 : 
    6854            4 :         Ok(())
    6855            4 :     }
    6856              : 
    6857              :     #[tokio::test]
    6858            4 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6859            4 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6860            4 : 
    6861            4 :         let (tenant, ctx) = harness.load().await;
    6862            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6863            4 :         let (tline, ctx) = tenant
    6864            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6865            4 :             .await?;
    6866            4 :         let tline = tline.raw_timeline().unwrap();
    6867            4 : 
    6868            4 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6869            4 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6870            4 :         modification.set_lsn(Lsn(0x1008))?;
    6871            4 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6872            4 :         modification.commit(&ctx).await?;
    6873            4 : 
    6874            4 :         let child_timeline_id = TimelineId::generate();
    6875            4 :         tenant
    6876            4 :             .branch_timeline_test(
    6877            4 :                 tline,
    6878            4 :                 child_timeline_id,
    6879            4 :                 Some(tline.get_last_record_lsn()),
    6880            4 :                 &ctx,
    6881            4 :             )
    6882            4 :             .await?;
    6883            4 : 
    6884            4 :         let child_timeline = tenant
    6885            4 :             .get_timeline(child_timeline_id, true)
    6886            4 :             .expect("Should have the branched timeline");
    6887            4 : 
    6888            4 :         let aux_keyspace = KeySpace {
    6889            4 :             ranges: vec![NON_INHERITED_RANGE],
    6890            4 :         };
    6891            4 :         let read_lsn = child_timeline.get_last_record_lsn();
    6892            4 : 
    6893            4 :         let vectored_res = child_timeline
    6894            4 :             .get_vectored_impl(
    6895            4 :                 aux_keyspace.clone(),
    6896            4 :                 read_lsn,
    6897            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6898            4 :                 &ctx,
    6899            4 :             )
    6900            4 :             .await;
    6901            4 : 
    6902            4 :         let images = vectored_res?;
    6903            4 :         assert!(images.is_empty());
    6904            4 :         Ok(())
    6905            4 :     }
    6906              : 
    6907              :     // Test that vectored get handles layer gaps correctly
    6908              :     // by advancing into the next ancestor timeline if required.
    6909              :     //
    6910              :     // The test generates timelines that look like the diagram below.
    6911              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6912              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6913              :     //
    6914              :     // ```
    6915              :     //-------------------------------+
    6916              :     //                          ...  |
    6917              :     //               [   L1   ]      |
    6918              :     //     [ / L1   ]                | Child Timeline
    6919              :     // ...                           |
    6920              :     // ------------------------------+
    6921              :     //     [ X L1   ]                | Parent Timeline
    6922              :     // ------------------------------+
    6923              :     // ```
    6924              :     #[tokio::test]
    6925            4 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6926            4 :         let tenant_conf = TenantConf {
    6927            4 :             // Make compaction deterministic
    6928            4 :             gc_period: Duration::ZERO,
    6929            4 :             compaction_period: Duration::ZERO,
    6930            4 :             // Encourage creation of L1 layers
    6931            4 :             checkpoint_distance: 16 * 1024,
    6932            4 :             compaction_target_size: 8 * 1024,
    6933            4 :             ..TenantConf::default()
    6934            4 :         };
    6935            4 : 
    6936            4 :         let harness = TenantHarness::create_custom(
    6937            4 :             "test_get_vectored_key_gap",
    6938            4 :             tenant_conf,
    6939            4 :             TenantId::generate(),
    6940            4 :             ShardIdentity::unsharded(),
    6941            4 :             Generation::new(0xdeadbeef),
    6942            4 :         )
    6943            4 :         .await?;
    6944            4 :         let (tenant, ctx) = harness.load().await;
    6945            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6946            4 : 
    6947            4 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6948            4 :         let gap_at_key = current_key.add(100);
    6949            4 :         let mut current_lsn = Lsn(0x10);
    6950            4 : 
    6951            4 :         const KEY_COUNT: usize = 10_000;
    6952            4 : 
    6953            4 :         let timeline_id = TimelineId::generate();
    6954            4 :         let current_timeline = tenant
    6955            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6956            4 :             .await?;
    6957            4 : 
    6958            4 :         current_lsn += 0x100;
    6959            4 : 
    6960            4 :         let mut writer = current_timeline.writer().await;
    6961            4 :         writer
    6962            4 :             .put(
    6963            4 :                 gap_at_key,
    6964            4 :                 current_lsn,
    6965            4 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6966            4 :                 &ctx,
    6967            4 :             )
    6968            4 :             .await?;
    6969            4 :         writer.finish_write(current_lsn);
    6970            4 :         drop(writer);
    6971            4 : 
    6972            4 :         let mut latest_lsns = HashMap::new();
    6973            4 :         latest_lsns.insert(gap_at_key, current_lsn);
    6974            4 : 
    6975            4 :         current_timeline.freeze_and_flush().await?;
    6976            4 : 
    6977            4 :         let child_timeline_id = TimelineId::generate();
    6978            4 : 
    6979            4 :         tenant
    6980            4 :             .branch_timeline_test(
    6981            4 :                 &current_timeline,
    6982            4 :                 child_timeline_id,
    6983            4 :                 Some(current_lsn),
    6984            4 :                 &ctx,
    6985            4 :             )
    6986            4 :             .await?;
    6987            4 :         let child_timeline = tenant
    6988            4 :             .get_timeline(child_timeline_id, true)
    6989            4 :             .expect("Should have the branched timeline");
    6990            4 : 
    6991        40004 :         for i in 0..KEY_COUNT {
    6992        40000 :             if current_key == gap_at_key {
    6993            4 :                 current_key = current_key.next();
    6994            4 :                 continue;
    6995        39996 :             }
    6996        39996 : 
    6997        39996 :             current_lsn += 0x10;
    6998            4 : 
    6999        39996 :             let mut writer = child_timeline.writer().await;
    7000        39996 :             writer
    7001        39996 :                 .put(
    7002        39996 :                     current_key,
    7003        39996 :                     current_lsn,
    7004        39996 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    7005        39996 :                     &ctx,
    7006        39996 :                 )
    7007        39996 :                 .await?;
    7008        39996 :             writer.finish_write(current_lsn);
    7009        39996 :             drop(writer);
    7010        39996 : 
    7011        39996 :             latest_lsns.insert(current_key, current_lsn);
    7012        39996 :             current_key = current_key.next();
    7013        39996 : 
    7014        39996 :             // Flush every now and then to encourage layer file creation.
    7015        39996 :             if i % 500 == 0 {
    7016           80 :                 child_timeline.freeze_and_flush().await?;
    7017        39916 :             }
    7018            4 :         }
    7019            4 : 
    7020            4 :         child_timeline.freeze_and_flush().await?;
    7021            4 :         let mut flags = EnumSet::new();
    7022            4 :         flags.insert(CompactFlags::ForceRepartition);
    7023            4 :         child_timeline
    7024            4 :             .compact(&CancellationToken::new(), flags, &ctx)
    7025            4 :             .await?;
    7026            4 : 
    7027            4 :         let key_near_end = {
    7028            4 :             let mut tmp = current_key;
    7029            4 :             tmp.field6 -= 10;
    7030            4 :             tmp
    7031            4 :         };
    7032            4 : 
    7033            4 :         let key_near_gap = {
    7034            4 :             let mut tmp = gap_at_key;
    7035            4 :             tmp.field6 -= 10;
    7036            4 :             tmp
    7037            4 :         };
    7038            4 : 
    7039            4 :         let read = KeySpace {
    7040            4 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7041            4 :         };
    7042            4 :         let results = child_timeline
    7043            4 :             .get_vectored_impl(
    7044            4 :                 read.clone(),
    7045            4 :                 current_lsn,
    7046            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7047            4 :                 &ctx,
    7048            4 :             )
    7049            4 :             .await?;
    7050            4 : 
    7051           88 :         for (key, img_res) in results {
    7052           84 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7053           84 :             assert_eq!(img_res?, expected);
    7054            4 :         }
    7055            4 : 
    7056            4 :         Ok(())
    7057            4 :     }
    7058              : 
    7059              :     // Test that vectored get descends into ancestor timelines correctly and
    7060              :     // does not return an image that's newer than requested.
    7061              :     //
    7062              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7063              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7064              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7065              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7066              :     // order to avoid returning an image that's too new. The test below constructs such
    7067              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7068              :     // ```
    7069              :     //    LSN
    7070              :     //     ^
    7071              :     //     |
    7072              :     //     |
    7073              :     // 500 | --------------------------------------> branch point
    7074              :     // 400 |        X
    7075              :     // 300 |        X
    7076              :     // 200 | --------------------------------------> requested lsn
    7077              :     // 100 |        X
    7078              :     //     |---------------------------------------> Key
    7079              :     //              |
    7080              :     //              ------> requested key
    7081              :     //
    7082              :     // Legend:
    7083              :     // * X - page images
    7084              :     // ```
    7085              :     #[tokio::test]
    7086            4 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7087            4 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7088            4 :         let (tenant, ctx) = harness.load().await;
    7089            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7090            4 : 
    7091            4 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7092            4 :         let end_key = start_key.add(1000);
    7093            4 :         let child_gap_at_key = start_key.add(500);
    7094            4 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7095            4 : 
    7096            4 :         let mut current_lsn = Lsn(0x10);
    7097            4 : 
    7098            4 :         let timeline_id = TimelineId::generate();
    7099            4 :         let parent_timeline = tenant
    7100            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7101            4 :             .await?;
    7102            4 : 
    7103            4 :         current_lsn += 0x100;
    7104            4 : 
    7105           16 :         for _ in 0..3 {
    7106           12 :             let mut key = start_key;
    7107        12012 :             while key < end_key {
    7108        12000 :                 current_lsn += 0x10;
    7109        12000 : 
    7110        12000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    7111            4 : 
    7112        12000 :                 let mut writer = parent_timeline.writer().await;
    7113        12000 :                 writer
    7114        12000 :                     .put(
    7115        12000 :                         key,
    7116        12000 :                         current_lsn,
    7117        12000 :                         &Value::Image(test_img(&image_value)),
    7118        12000 :                         &ctx,
    7119        12000 :                     )
    7120        12000 :                     .await?;
    7121        12000 :                 writer.finish_write(current_lsn);
    7122        12000 : 
    7123        12000 :                 if key == child_gap_at_key {
    7124           12 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7125        11988 :                 }
    7126            4 : 
    7127        12000 :                 key = key.next();
    7128            4 :             }
    7129            4 : 
    7130           12 :             parent_timeline.freeze_and_flush().await?;
    7131            4 :         }
    7132            4 : 
    7133            4 :         let child_timeline_id = TimelineId::generate();
    7134            4 : 
    7135            4 :         let child_timeline = tenant
    7136            4 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7137            4 :             .await?;
    7138            4 : 
    7139            4 :         let mut key = start_key;
    7140         4004 :         while key < end_key {
    7141         4000 :             if key == child_gap_at_key {
    7142            4 :                 key = key.next();
    7143            4 :                 continue;
    7144         3996 :             }
    7145         3996 : 
    7146         3996 :             current_lsn += 0x10;
    7147            4 : 
    7148         3996 :             let mut writer = child_timeline.writer().await;
    7149         3996 :             writer
    7150         3996 :                 .put(
    7151         3996 :                     key,
    7152         3996 :                     current_lsn,
    7153         3996 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    7154         3996 :                     &ctx,
    7155         3996 :                 )
    7156         3996 :                 .await?;
    7157         3996 :             writer.finish_write(current_lsn);
    7158         3996 : 
    7159         3996 :             key = key.next();
    7160            4 :         }
    7161            4 : 
    7162            4 :         child_timeline.freeze_and_flush().await?;
    7163            4 : 
    7164            4 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7165            4 :         let mut query_lsns = Vec::new();
    7166           12 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7167           72 :             for offset in lsn_offsets {
    7168           60 :                 query_lsns.push(Lsn(image_lsn
    7169           60 :                     .0
    7170           60 :                     .checked_add_signed(offset)
    7171           60 :                     .expect("Shouldn't overflow")));
    7172           60 :             }
    7173            4 :         }
    7174            4 : 
    7175           64 :         for query_lsn in query_lsns {
    7176           60 :             let results = child_timeline
    7177           60 :                 .get_vectored_impl(
    7178           60 :                     KeySpace {
    7179           60 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7180           60 :                     },
    7181           60 :                     query_lsn,
    7182           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7183           60 :                     &ctx,
    7184           60 :                 )
    7185           60 :                 .await;
    7186            4 : 
    7187           60 :             let expected_item = parent_gap_lsns
    7188           60 :                 .iter()
    7189           60 :                 .rev()
    7190          136 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7191           60 : 
    7192           60 :             info!(
    7193            4 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7194            4 :                 query_lsn, expected_item
    7195            4 :             );
    7196            4 : 
    7197           60 :             match expected_item {
    7198           52 :                 Some((_, img_value)) => {
    7199           52 :                     let key_results = results.expect("No vectored get error expected");
    7200           52 :                     let key_result = &key_results[&child_gap_at_key];
    7201           52 :                     let returned_img = key_result
    7202           52 :                         .as_ref()
    7203           52 :                         .expect("No page reconstruct error expected");
    7204           52 : 
    7205           52 :                     info!(
    7206            4 :                         "Vectored read at LSN {} returned image {}",
    7207            0 :                         query_lsn,
    7208            0 :                         std::str::from_utf8(returned_img)?
    7209            4 :                     );
    7210           52 :                     assert_eq!(*returned_img, test_img(img_value));
    7211            4 :                 }
    7212            4 :                 None => {
    7213            8 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7214            4 :                 }
    7215            4 :             }
    7216            4 :         }
    7217            4 : 
    7218            4 :         Ok(())
    7219            4 :     }
    7220              : 
    7221              :     #[tokio::test]
    7222            4 :     async fn test_random_updates() -> anyhow::Result<()> {
    7223            4 :         let names_algorithms = [
    7224            4 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7225            4 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7226            4 :         ];
    7227           12 :         for (name, algorithm) in names_algorithms {
    7228            8 :             test_random_updates_algorithm(name, algorithm).await?;
    7229            4 :         }
    7230            4 :         Ok(())
    7231            4 :     }
    7232              : 
    7233            8 :     async fn test_random_updates_algorithm(
    7234            8 :         name: &'static str,
    7235            8 :         compaction_algorithm: CompactionAlgorithm,
    7236            8 :     ) -> anyhow::Result<()> {
    7237            8 :         let mut harness = TenantHarness::create(name).await?;
    7238            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7239            8 :             kind: compaction_algorithm,
    7240            8 :         };
    7241            8 :         let (tenant, ctx) = harness.load().await;
    7242            8 :         let tline = tenant
    7243            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7244            8 :             .await?;
    7245              : 
    7246              :         const NUM_KEYS: usize = 1000;
    7247            8 :         let cancel = CancellationToken::new();
    7248            8 : 
    7249            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7250            8 :         let mut test_key_end = test_key;
    7251            8 :         test_key_end.field6 = NUM_KEYS as u32;
    7252            8 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7253            8 : 
    7254            8 :         let mut keyspace = KeySpaceAccum::new();
    7255            8 : 
    7256            8 :         // Track when each page was last modified. Used to assert that
    7257            8 :         // a read sees the latest page version.
    7258            8 :         let mut updated = [Lsn(0); NUM_KEYS];
    7259            8 : 
    7260            8 :         let mut lsn = Lsn(0x10);
    7261              :         #[allow(clippy::needless_range_loop)]
    7262         8008 :         for blknum in 0..NUM_KEYS {
    7263         8000 :             lsn = Lsn(lsn.0 + 0x10);
    7264         8000 :             test_key.field6 = blknum as u32;
    7265         8000 :             let mut writer = tline.writer().await;
    7266         8000 :             writer
    7267         8000 :                 .put(
    7268         8000 :                     test_key,
    7269         8000 :                     lsn,
    7270         8000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7271         8000 :                     &ctx,
    7272         8000 :                 )
    7273         8000 :                 .await?;
    7274         8000 :             writer.finish_write(lsn);
    7275         8000 :             updated[blknum] = lsn;
    7276         8000 :             drop(writer);
    7277         8000 : 
    7278         8000 :             keyspace.add_key(test_key);
    7279              :         }
    7280              : 
    7281          408 :         for _ in 0..50 {
    7282       400400 :             for _ in 0..NUM_KEYS {
    7283       400000 :                 lsn = Lsn(lsn.0 + 0x10);
    7284       400000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7285       400000 :                 test_key.field6 = blknum as u32;
    7286       400000 :                 let mut writer = tline.writer().await;
    7287       400000 :                 writer
    7288       400000 :                     .put(
    7289       400000 :                         test_key,
    7290       400000 :                         lsn,
    7291       400000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7292       400000 :                         &ctx,
    7293       400000 :                     )
    7294       400000 :                     .await?;
    7295       400000 :                 writer.finish_write(lsn);
    7296       400000 :                 drop(writer);
    7297       400000 :                 updated[blknum] = lsn;
    7298              :             }
    7299              : 
    7300              :             // Read all the blocks
    7301       400000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7302       400000 :                 test_key.field6 = blknum as u32;
    7303       400000 :                 assert_eq!(
    7304       400000 :                     tline.get(test_key, lsn, &ctx).await?,
    7305       400000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7306              :                 );
    7307              :             }
    7308              : 
    7309              :             // Perform a cycle of flush, and GC
    7310          400 :             tline.freeze_and_flush().await?;
    7311          400 :             tenant
    7312          400 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7313          400 :                 .await?;
    7314              :         }
    7315              : 
    7316            8 :         Ok(())
    7317            8 :     }
    7318              : 
    7319              :     #[tokio::test]
    7320            4 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7321            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7322            4 :             .await?
    7323            4 :             .load()
    7324            4 :             .await;
    7325            4 :         let mut tline = tenant
    7326            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7327            4 :             .await?;
    7328            4 : 
    7329            4 :         const NUM_KEYS: usize = 1000;
    7330            4 : 
    7331            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7332            4 : 
    7333            4 :         let mut keyspace = KeySpaceAccum::new();
    7334            4 : 
    7335            4 :         let cancel = CancellationToken::new();
    7336            4 : 
    7337            4 :         // Track when each page was last modified. Used to assert that
    7338            4 :         // a read sees the latest page version.
    7339            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7340            4 : 
    7341            4 :         let mut lsn = Lsn(0x10);
    7342            4 :         #[allow(clippy::needless_range_loop)]
    7343         4004 :         for blknum in 0..NUM_KEYS {
    7344         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7345         4000 :             test_key.field6 = blknum as u32;
    7346         4000 :             let mut writer = tline.writer().await;
    7347         4000 :             writer
    7348         4000 :                 .put(
    7349         4000 :                     test_key,
    7350         4000 :                     lsn,
    7351         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7352         4000 :                     &ctx,
    7353         4000 :                 )
    7354         4000 :                 .await?;
    7355         4000 :             writer.finish_write(lsn);
    7356         4000 :             updated[blknum] = lsn;
    7357         4000 :             drop(writer);
    7358         4000 : 
    7359         4000 :             keyspace.add_key(test_key);
    7360            4 :         }
    7361            4 : 
    7362          204 :         for _ in 0..50 {
    7363          200 :             let new_tline_id = TimelineId::generate();
    7364          200 :             tenant
    7365          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7366          200 :                 .await?;
    7367          200 :             tline = tenant
    7368          200 :                 .get_timeline(new_tline_id, true)
    7369          200 :                 .expect("Should have the branched timeline");
    7370            4 : 
    7371       200200 :             for _ in 0..NUM_KEYS {
    7372       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7373       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7374       200000 :                 test_key.field6 = blknum as u32;
    7375       200000 :                 let mut writer = tline.writer().await;
    7376       200000 :                 writer
    7377       200000 :                     .put(
    7378       200000 :                         test_key,
    7379       200000 :                         lsn,
    7380       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7381       200000 :                         &ctx,
    7382       200000 :                     )
    7383       200000 :                     .await?;
    7384       200000 :                 println!("updating {} at {}", blknum, lsn);
    7385       200000 :                 writer.finish_write(lsn);
    7386       200000 :                 drop(writer);
    7387       200000 :                 updated[blknum] = lsn;
    7388            4 :             }
    7389            4 : 
    7390            4 :             // Read all the blocks
    7391       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7392       200000 :                 test_key.field6 = blknum as u32;
    7393       200000 :                 assert_eq!(
    7394       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7395       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7396            4 :                 );
    7397            4 :             }
    7398            4 : 
    7399            4 :             // Perform a cycle of flush, compact, and GC
    7400          200 :             tline.freeze_and_flush().await?;
    7401          200 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7402          200 :             tenant
    7403          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7404          200 :                 .await?;
    7405            4 :         }
    7406            4 : 
    7407            4 :         Ok(())
    7408            4 :     }
    7409              : 
    7410              :     #[tokio::test]
    7411            4 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7412            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7413            4 :             .await?
    7414            4 :             .load()
    7415            4 :             .await;
    7416            4 :         let mut tline = tenant
    7417            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7418            4 :             .await?;
    7419            4 : 
    7420            4 :         const NUM_KEYS: usize = 100;
    7421            4 :         const NUM_TLINES: usize = 50;
    7422            4 : 
    7423            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7424            4 :         // Track page mutation lsns across different timelines.
    7425            4 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7426            4 : 
    7427            4 :         let mut lsn = Lsn(0x10);
    7428            4 : 
    7429            4 :         #[allow(clippy::needless_range_loop)]
    7430          204 :         for idx in 0..NUM_TLINES {
    7431          200 :             let new_tline_id = TimelineId::generate();
    7432          200 :             tenant
    7433          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7434          200 :                 .await?;
    7435          200 :             tline = tenant
    7436          200 :                 .get_timeline(new_tline_id, true)
    7437          200 :                 .expect("Should have the branched timeline");
    7438            4 : 
    7439        20200 :             for _ in 0..NUM_KEYS {
    7440        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7441        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7442        20000 :                 test_key.field6 = blknum as u32;
    7443        20000 :                 let mut writer = tline.writer().await;
    7444        20000 :                 writer
    7445        20000 :                     .put(
    7446        20000 :                         test_key,
    7447        20000 :                         lsn,
    7448        20000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7449        20000 :                         &ctx,
    7450        20000 :                     )
    7451        20000 :                     .await?;
    7452        20000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7453        20000 :                 writer.finish_write(lsn);
    7454        20000 :                 drop(writer);
    7455        20000 :                 updated[idx][blknum] = lsn;
    7456            4 :             }
    7457            4 :         }
    7458            4 : 
    7459            4 :         // Read pages from leaf timeline across all ancestors.
    7460          200 :         for (idx, lsns) in updated.iter().enumerate() {
    7461        20000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7462            4 :                 // Skip empty mutations.
    7463        20000 :                 if lsn.0 == 0 {
    7464         7426 :                     continue;
    7465        12574 :                 }
    7466        12574 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7467        12574 :                 test_key.field6 = blknum as u32;
    7468        12574 :                 assert_eq!(
    7469        12574 :                     tline.get(test_key, *lsn, &ctx).await?,
    7470        12574 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7471            4 :                 );
    7472            4 :             }
    7473            4 :         }
    7474            4 :         Ok(())
    7475            4 :     }
    7476              : 
    7477              :     #[tokio::test]
    7478            4 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7479            4 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7480            4 :             .await?
    7481            4 :             .load()
    7482            4 :             .await;
    7483            4 : 
    7484            4 :         let initdb_lsn = Lsn(0x20);
    7485            4 :         let (utline, ctx) = tenant
    7486            4 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7487            4 :             .await?;
    7488            4 :         let tline = utline.raw_timeline().unwrap();
    7489            4 : 
    7490            4 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7491            4 :         tline.maybe_spawn_flush_loop();
    7492            4 : 
    7493            4 :         // Make sure the timeline has the minimum set of required keys for operation.
    7494            4 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7495            4 :         // Except if you `put` at `initdb_lsn`.
    7496            4 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7497            4 :         // It uses `repartition()`, which assumes some keys to be present.
    7498            4 :         // Let's make sure the test timeline can handle that case.
    7499            4 :         {
    7500            4 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7501            4 :             assert_eq!(
    7502            4 :                 timeline::FlushLoopState::Running {
    7503            4 :                     expect_initdb_optimization: false,
    7504            4 :                     initdb_optimization_count: 0,
    7505            4 :                 },
    7506            4 :                 *state
    7507            4 :             );
    7508            4 :             *state = timeline::FlushLoopState::Running {
    7509            4 :                 expect_initdb_optimization: true,
    7510            4 :                 initdb_optimization_count: 0,
    7511            4 :             };
    7512            4 :         }
    7513            4 : 
    7514            4 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7515            4 :         // As explained above, the optimization requires some keys to be present.
    7516            4 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7517            4 :         // This is what `create_test_timeline` does, by the way.
    7518            4 :         let mut modification = tline.begin_modification(initdb_lsn);
    7519            4 :         modification
    7520            4 :             .init_empty_test_timeline()
    7521            4 :             .context("init_empty_test_timeline")?;
    7522            4 :         modification
    7523            4 :             .commit(&ctx)
    7524            4 :             .await
    7525            4 :             .context("commit init_empty_test_timeline modification")?;
    7526            4 : 
    7527            4 :         // Do the flush. The flush code will check the expectations that we set above.
    7528            4 :         tline.freeze_and_flush().await?;
    7529            4 : 
    7530            4 :         // assert freeze_and_flush exercised the initdb optimization
    7531            4 :         {
    7532            4 :             let state = tline.flush_loop_state.lock().unwrap();
    7533            4 :             let timeline::FlushLoopState::Running {
    7534            4 :                 expect_initdb_optimization,
    7535            4 :                 initdb_optimization_count,
    7536            4 :             } = *state
    7537            4 :             else {
    7538            4 :                 panic!("unexpected state: {:?}", *state);
    7539            4 :             };
    7540            4 :             assert!(expect_initdb_optimization);
    7541            4 :             assert!(initdb_optimization_count > 0);
    7542            4 :         }
    7543            4 :         Ok(())
    7544            4 :     }
    7545              : 
    7546              :     #[tokio::test]
    7547            4 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7548            4 :         let name = "test_create_guard_crash";
    7549            4 :         let harness = TenantHarness::create(name).await?;
    7550            4 :         {
    7551            4 :             let (tenant, ctx) = harness.load().await;
    7552            4 :             let (tline, _ctx) = tenant
    7553            4 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7554            4 :                 .await?;
    7555            4 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7556            4 :             let raw_tline = tline.raw_timeline().unwrap();
    7557            4 :             raw_tline
    7558            4 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7559            4 :                 .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
    7560            4 :                 .await;
    7561            4 :             std::mem::forget(tline);
    7562            4 :         }
    7563            4 : 
    7564            4 :         let (tenant, _) = harness.load().await;
    7565            4 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7566            4 :             Ok(_) => panic!("timeline should've been removed during load"),
    7567            4 :             Err(e) => {
    7568            4 :                 assert_eq!(
    7569            4 :                     e,
    7570            4 :                     GetTimelineError::NotFound {
    7571            4 :                         tenant_id: tenant.tenant_shard_id,
    7572            4 :                         timeline_id: TIMELINE_ID,
    7573            4 :                     }
    7574            4 :                 )
    7575            4 :             }
    7576            4 :         }
    7577            4 : 
    7578            4 :         assert!(
    7579            4 :             !harness
    7580            4 :                 .conf
    7581            4 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7582            4 :                 .exists()
    7583            4 :         );
    7584            4 : 
    7585            4 :         Ok(())
    7586            4 :     }
    7587              : 
    7588              :     #[tokio::test]
    7589            4 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7590            4 :         let names_algorithms = [
    7591            4 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7592            4 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7593            4 :         ];
    7594           12 :         for (name, algorithm) in names_algorithms {
    7595            8 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7596            4 :         }
    7597            4 :         Ok(())
    7598            4 :     }
    7599              : 
    7600            8 :     async fn test_read_at_max_lsn_algorithm(
    7601            8 :         name: &'static str,
    7602            8 :         compaction_algorithm: CompactionAlgorithm,
    7603            8 :     ) -> anyhow::Result<()> {
    7604            8 :         let mut harness = TenantHarness::create(name).await?;
    7605            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7606            8 :             kind: compaction_algorithm,
    7607            8 :         };
    7608            8 :         let (tenant, ctx) = harness.load().await;
    7609            8 :         let tline = tenant
    7610            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7611            8 :             .await?;
    7612              : 
    7613            8 :         let lsn = Lsn(0x10);
    7614            8 :         let compact = false;
    7615            8 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7616              : 
    7617            8 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7618            8 :         let read_lsn = Lsn(u64::MAX - 1);
    7619              : 
    7620            8 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7621            8 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7622              : 
    7623            8 :         Ok(())
    7624            8 :     }
    7625              : 
    7626              :     #[tokio::test]
    7627            4 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7628            4 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7629            4 :         let (tenant, ctx) = harness.load().await;
    7630            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7631            4 :         let tline = tenant
    7632            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7633            4 :             .await?;
    7634            4 : 
    7635            4 :         const NUM_KEYS: usize = 1000;
    7636            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7637            4 : 
    7638            4 :         let cancel = CancellationToken::new();
    7639            4 : 
    7640            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7641            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7642            4 :         let mut test_key = base_key;
    7643            4 : 
    7644            4 :         // Track when each page was last modified. Used to assert that
    7645            4 :         // a read sees the latest page version.
    7646            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7647            4 : 
    7648            4 :         let mut lsn = Lsn(0x10);
    7649            4 :         #[allow(clippy::needless_range_loop)]
    7650         4004 :         for blknum in 0..NUM_KEYS {
    7651         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7652         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7653         4000 :             let mut writer = tline.writer().await;
    7654         4000 :             writer
    7655         4000 :                 .put(
    7656         4000 :                     test_key,
    7657         4000 :                     lsn,
    7658         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7659         4000 :                     &ctx,
    7660         4000 :                 )
    7661         4000 :                 .await?;
    7662         4000 :             writer.finish_write(lsn);
    7663         4000 :             updated[blknum] = lsn;
    7664         4000 :             drop(writer);
    7665            4 :         }
    7666            4 : 
    7667            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7668            4 : 
    7669           48 :         for iter in 0..=10 {
    7670            4 :             // Read all the blocks
    7671        44000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7672        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7673        44000 :                 assert_eq!(
    7674        44000 :                     tline.get(test_key, lsn, &ctx).await?,
    7675        44000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7676            4 :                 );
    7677            4 :             }
    7678            4 : 
    7679           44 :             let mut cnt = 0;
    7680        44000 :             for (key, value) in tline
    7681           44 :                 .get_vectored_impl(
    7682           44 :                     keyspace.clone(),
    7683           44 :                     lsn,
    7684           44 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7685           44 :                     &ctx,
    7686           44 :                 )
    7687           44 :                 .await?
    7688            4 :             {
    7689        44000 :                 let blknum = key.field6 as usize;
    7690        44000 :                 let value = value?;
    7691        44000 :                 assert!(blknum % STEP == 0);
    7692        44000 :                 let blknum = blknum / STEP;
    7693        44000 :                 assert_eq!(
    7694        44000 :                     value,
    7695        44000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7696        44000 :                 );
    7697        44000 :                 cnt += 1;
    7698            4 :             }
    7699            4 : 
    7700           44 :             assert_eq!(cnt, NUM_KEYS);
    7701            4 : 
    7702        44044 :             for _ in 0..NUM_KEYS {
    7703        44000 :                 lsn = Lsn(lsn.0 + 0x10);
    7704        44000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7705        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7706        44000 :                 let mut writer = tline.writer().await;
    7707        44000 :                 writer
    7708        44000 :                     .put(
    7709        44000 :                         test_key,
    7710        44000 :                         lsn,
    7711        44000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7712        44000 :                         &ctx,
    7713        44000 :                     )
    7714        44000 :                     .await?;
    7715        44000 :                 writer.finish_write(lsn);
    7716        44000 :                 drop(writer);
    7717        44000 :                 updated[blknum] = lsn;
    7718            4 :             }
    7719            4 : 
    7720            4 :             // Perform two cycles of flush, compact, and GC
    7721          132 :             for round in 0..2 {
    7722           88 :                 tline.freeze_and_flush().await?;
    7723           88 :                 tline
    7724           88 :                     .compact(
    7725           88 :                         &cancel,
    7726           88 :                         if iter % 5 == 0 && round == 0 {
    7727           12 :                             let mut flags = EnumSet::new();
    7728           12 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7729           12 :                             flags.insert(CompactFlags::ForceRepartition);
    7730           12 :                             flags
    7731            4 :                         } else {
    7732           76 :                             EnumSet::empty()
    7733            4 :                         },
    7734           88 :                         &ctx,
    7735           88 :                     )
    7736           88 :                     .await?;
    7737           88 :                 tenant
    7738           88 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7739           88 :                     .await?;
    7740            4 :             }
    7741            4 :         }
    7742            4 : 
    7743            4 :         Ok(())
    7744            4 :     }
    7745              : 
    7746              :     #[tokio::test]
    7747            4 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7748            4 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7749            4 :         let (tenant, ctx) = harness.load().await;
    7750            4 :         let tline = tenant
    7751            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7752            4 :             .await?;
    7753            4 : 
    7754            4 :         let cancel = CancellationToken::new();
    7755            4 : 
    7756            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7757            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7758            4 :         let test_key = base_key;
    7759            4 :         let mut lsn = Lsn(0x10);
    7760            4 : 
    7761           84 :         for _ in 0..20 {
    7762           80 :             lsn = Lsn(lsn.0 + 0x10);
    7763           80 :             let mut writer = tline.writer().await;
    7764           80 :             writer
    7765           80 :                 .put(
    7766           80 :                     test_key,
    7767           80 :                     lsn,
    7768           80 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7769           80 :                     &ctx,
    7770           80 :                 )
    7771           80 :                 .await?;
    7772           80 :             writer.finish_write(lsn);
    7773           80 :             drop(writer);
    7774           80 :             tline.freeze_and_flush().await?; // force create a delta layer
    7775            4 :         }
    7776            4 : 
    7777            4 :         let before_num_l0_delta_files =
    7778            4 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7779            4 : 
    7780            4 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7781            4 : 
    7782            4 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7783            4 : 
    7784            4 :         assert!(
    7785            4 :             after_num_l0_delta_files < before_num_l0_delta_files,
    7786            4 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    7787            4 :         );
    7788            4 : 
    7789            4 :         assert_eq!(
    7790            4 :             tline.get(test_key, lsn, &ctx).await?,
    7791            4 :             test_img(&format!("{} at {}", 0, lsn))
    7792            4 :         );
    7793            4 : 
    7794            4 :         Ok(())
    7795            4 :     }
    7796              : 
    7797              :     #[tokio::test]
    7798            4 :     async fn test_aux_file_e2e() {
    7799            4 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7800            4 : 
    7801            4 :         let (tenant, ctx) = harness.load().await;
    7802            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7803            4 : 
    7804            4 :         let mut lsn = Lsn(0x08);
    7805            4 : 
    7806            4 :         let tline: Arc<Timeline> = tenant
    7807            4 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7808            4 :             .await
    7809            4 :             .unwrap();
    7810            4 : 
    7811            4 :         {
    7812            4 :             lsn += 8;
    7813            4 :             let mut modification = tline.begin_modification(lsn);
    7814            4 :             modification
    7815            4 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7816            4 :                 .await
    7817            4 :                 .unwrap();
    7818            4 :             modification.commit(&ctx).await.unwrap();
    7819            4 :         }
    7820            4 : 
    7821            4 :         // we can read everything from the storage
    7822            4 :         let files = tline
    7823            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7824            4 :             .await
    7825            4 :             .unwrap();
    7826            4 :         assert_eq!(
    7827            4 :             files.get("pg_logical/mappings/test1"),
    7828            4 :             Some(&bytes::Bytes::from_static(b"first"))
    7829            4 :         );
    7830            4 : 
    7831            4 :         {
    7832            4 :             lsn += 8;
    7833            4 :             let mut modification = tline.begin_modification(lsn);
    7834            4 :             modification
    7835            4 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7836            4 :                 .await
    7837            4 :                 .unwrap();
    7838            4 :             modification.commit(&ctx).await.unwrap();
    7839            4 :         }
    7840            4 : 
    7841            4 :         let files = tline
    7842            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7843            4 :             .await
    7844            4 :             .unwrap();
    7845            4 :         assert_eq!(
    7846            4 :             files.get("pg_logical/mappings/test2"),
    7847            4 :             Some(&bytes::Bytes::from_static(b"second"))
    7848            4 :         );
    7849            4 : 
    7850            4 :         let child = tenant
    7851            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7852            4 :             .await
    7853            4 :             .unwrap();
    7854            4 : 
    7855            4 :         let files = child
    7856            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7857            4 :             .await
    7858            4 :             .unwrap();
    7859            4 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7860            4 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7861            4 :     }
    7862              : 
    7863              :     #[tokio::test]
    7864            4 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7865            4 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7866            4 :         let (tenant, ctx) = harness.load().await;
    7867            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7868            4 :         let tline = tenant
    7869            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7870            4 :             .await?;
    7871            4 : 
    7872            4 :         const NUM_KEYS: usize = 1000;
    7873            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7874            4 : 
    7875            4 :         let cancel = CancellationToken::new();
    7876            4 : 
    7877            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7878            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7879            4 :         let mut test_key = base_key;
    7880            4 :         let mut lsn = Lsn(0x10);
    7881            4 : 
    7882           16 :         async fn scan_with_statistics(
    7883           16 :             tline: &Timeline,
    7884           16 :             keyspace: &KeySpace,
    7885           16 :             lsn: Lsn,
    7886           16 :             ctx: &RequestContext,
    7887           16 :             io_concurrency: IoConcurrency,
    7888           16 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7889           16 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    7890           16 :             let res = tline
    7891           16 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7892           16 :                 .await?;
    7893           16 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7894           16 :         }
    7895            4 : 
    7896            4 :         #[allow(clippy::needless_range_loop)]
    7897         4004 :         for blknum in 0..NUM_KEYS {
    7898         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7899         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7900         4000 :             let mut writer = tline.writer().await;
    7901         4000 :             writer
    7902         4000 :                 .put(
    7903         4000 :                     test_key,
    7904         4000 :                     lsn,
    7905         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7906         4000 :                     &ctx,
    7907         4000 :                 )
    7908         4000 :                 .await?;
    7909         4000 :             writer.finish_write(lsn);
    7910         4000 :             drop(writer);
    7911            4 :         }
    7912            4 : 
    7913            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7914            4 : 
    7915           44 :         for iter in 1..=10 {
    7916        40040 :             for _ in 0..NUM_KEYS {
    7917        40000 :                 lsn = Lsn(lsn.0 + 0x10);
    7918        40000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7919        40000 :                 test_key.field6 = (blknum * STEP) as u32;
    7920        40000 :                 let mut writer = tline.writer().await;
    7921        40000 :                 writer
    7922        40000 :                     .put(
    7923        40000 :                         test_key,
    7924        40000 :                         lsn,
    7925        40000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7926        40000 :                         &ctx,
    7927        40000 :                     )
    7928        40000 :                     .await?;
    7929        40000 :                 writer.finish_write(lsn);
    7930        40000 :                 drop(writer);
    7931            4 :             }
    7932            4 : 
    7933           40 :             tline.freeze_and_flush().await?;
    7934            4 : 
    7935           40 :             if iter % 5 == 0 {
    7936            8 :                 let (_, before_delta_file_accessed) =
    7937            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7938            8 :                         .await?;
    7939            8 :                 tline
    7940            8 :                     .compact(
    7941            8 :                         &cancel,
    7942            8 :                         {
    7943            8 :                             let mut flags = EnumSet::new();
    7944            8 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7945            8 :                             flags.insert(CompactFlags::ForceRepartition);
    7946            8 :                             flags
    7947            8 :                         },
    7948            8 :                         &ctx,
    7949            8 :                     )
    7950            8 :                     .await?;
    7951            8 :                 let (_, after_delta_file_accessed) =
    7952            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7953            8 :                         .await?;
    7954            8 :                 assert!(
    7955            8 :                     after_delta_file_accessed < before_delta_file_accessed,
    7956            4 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    7957            4 :                 );
    7958            4 :                 // Given that we already produced an image layer, there should be no delta layer needed for the scan, but still setting a low threshold there for unforeseen circumstances.
    7959            8 :                 assert!(
    7960            8 :                     after_delta_file_accessed <= 2,
    7961            4 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7962            4 :                 );
    7963           32 :             }
    7964            4 :         }
    7965            4 : 
    7966            4 :         Ok(())
    7967            4 :     }
    7968              : 
    7969              :     #[tokio::test]
    7970            4 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7971            4 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7972            4 :         let (tenant, ctx) = harness.load().await;
    7973            4 : 
    7974            4 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7975            4 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7976            4 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7977            4 : 
    7978            4 :         let tline = tenant
    7979            4 :             .create_test_timeline_with_layers(
    7980            4 :                 TIMELINE_ID,
    7981            4 :                 Lsn(0x10),
    7982            4 :                 DEFAULT_PG_VERSION,
    7983            4 :                 &ctx,
    7984            4 :                 Vec::new(), // in-memory layers
    7985            4 :                 Vec::new(), // delta layers
    7986            4 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7987            4 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    7988            4 :             )
    7989            4 :             .await?;
    7990            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7991            4 : 
    7992            4 :         let child = tenant
    7993            4 :             .branch_timeline_test_with_layers(
    7994            4 :                 &tline,
    7995            4 :                 NEW_TIMELINE_ID,
    7996            4 :                 Some(Lsn(0x20)),
    7997            4 :                 &ctx,
    7998            4 :                 Vec::new(), // delta layers
    7999            4 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8000            4 :                 Lsn(0x30),
    8001            4 :             )
    8002            4 :             .await
    8003            4 :             .unwrap();
    8004            4 : 
    8005            4 :         let lsn = Lsn(0x30);
    8006            4 : 
    8007            4 :         // test vectored get on parent timeline
    8008            4 :         assert_eq!(
    8009            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8010            4 :             Some(test_img("data key 1"))
    8011            4 :         );
    8012            4 :         assert!(
    8013            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8014            4 :                 .await
    8015            4 :                 .unwrap_err()
    8016            4 :                 .is_missing_key_error()
    8017            4 :         );
    8018            4 :         assert!(
    8019            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8020            4 :                 .await
    8021            4 :                 .unwrap_err()
    8022            4 :                 .is_missing_key_error()
    8023            4 :         );
    8024            4 : 
    8025            4 :         // test vectored get on child timeline
    8026            4 :         assert_eq!(
    8027            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8028            4 :             Some(test_img("data key 1"))
    8029            4 :         );
    8030            4 :         assert_eq!(
    8031            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8032            4 :             Some(test_img("data key 2"))
    8033            4 :         );
    8034            4 :         assert!(
    8035            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8036            4 :                 .await
    8037            4 :                 .unwrap_err()
    8038            4 :                 .is_missing_key_error()
    8039            4 :         );
    8040            4 : 
    8041            4 :         Ok(())
    8042            4 :     }
    8043              : 
    8044              :     #[tokio::test]
    8045            4 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8046            4 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8047            4 :         let (tenant, ctx) = harness.load().await;
    8048            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8049            4 : 
    8050            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8051            4 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8052            4 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8053            4 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8054            4 : 
    8055            4 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8056            4 :         let base_inherited_key_child =
    8057            4 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8058            4 :         let base_inherited_key_nonexist =
    8059            4 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8060            4 :         let base_inherited_key_overwrite =
    8061            4 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8062            4 : 
    8063            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8064            4 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8065            4 : 
    8066            4 :         let tline = tenant
    8067            4 :             .create_test_timeline_with_layers(
    8068            4 :                 TIMELINE_ID,
    8069            4 :                 Lsn(0x10),
    8070            4 :                 DEFAULT_PG_VERSION,
    8071            4 :                 &ctx,
    8072            4 :                 Vec::new(), // in-memory layers
    8073            4 :                 Vec::new(), // delta layers
    8074            4 :                 vec![(
    8075            4 :                     Lsn(0x20),
    8076            4 :                     vec![
    8077            4 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8078            4 :                         (
    8079            4 :                             base_inherited_key_overwrite,
    8080            4 :                             test_img("metadata key overwrite 1a"),
    8081            4 :                         ),
    8082            4 :                         (base_key, test_img("metadata key 1")),
    8083            4 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8084            4 :                     ],
    8085            4 :                 )], // image layers
    8086            4 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    8087            4 :             )
    8088            4 :             .await?;
    8089            4 : 
    8090            4 :         let child = tenant
    8091            4 :             .branch_timeline_test_with_layers(
    8092            4 :                 &tline,
    8093            4 :                 NEW_TIMELINE_ID,
    8094            4 :                 Some(Lsn(0x20)),
    8095            4 :                 &ctx,
    8096            4 :                 Vec::new(), // delta layers
    8097            4 :                 vec![(
    8098            4 :                     Lsn(0x30),
    8099            4 :                     vec![
    8100            4 :                         (
    8101            4 :                             base_inherited_key_child,
    8102            4 :                             test_img("metadata inherited key 2"),
    8103            4 :                         ),
    8104            4 :                         (
    8105            4 :                             base_inherited_key_overwrite,
    8106            4 :                             test_img("metadata key overwrite 2a"),
    8107            4 :                         ),
    8108            4 :                         (base_key_child, test_img("metadata key 2")),
    8109            4 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8110            4 :                     ],
    8111            4 :                 )], // image layers
    8112            4 :                 Lsn(0x30),
    8113            4 :             )
    8114            4 :             .await
    8115            4 :             .unwrap();
    8116            4 : 
    8117            4 :         let lsn = Lsn(0x30);
    8118            4 : 
    8119            4 :         // test vectored get on parent timeline
    8120            4 :         assert_eq!(
    8121            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8122            4 :             Some(test_img("metadata key 1"))
    8123            4 :         );
    8124            4 :         assert_eq!(
    8125            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8126            4 :             None
    8127            4 :         );
    8128            4 :         assert_eq!(
    8129            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8130            4 :             None
    8131            4 :         );
    8132            4 :         assert_eq!(
    8133            4 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8134            4 :             Some(test_img("metadata key overwrite 1b"))
    8135            4 :         );
    8136            4 :         assert_eq!(
    8137            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8138            4 :             Some(test_img("metadata inherited key 1"))
    8139            4 :         );
    8140            4 :         assert_eq!(
    8141            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8142            4 :             None
    8143            4 :         );
    8144            4 :         assert_eq!(
    8145            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8146            4 :             None
    8147            4 :         );
    8148            4 :         assert_eq!(
    8149            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8150            4 :             Some(test_img("metadata key overwrite 1a"))
    8151            4 :         );
    8152            4 : 
    8153            4 :         // test vectored get on child timeline
    8154            4 :         assert_eq!(
    8155            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8156            4 :             None
    8157            4 :         );
    8158            4 :         assert_eq!(
    8159            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8160            4 :             Some(test_img("metadata key 2"))
    8161            4 :         );
    8162            4 :         assert_eq!(
    8163            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8164            4 :             None
    8165            4 :         );
    8166            4 :         assert_eq!(
    8167            4 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8168            4 :             Some(test_img("metadata inherited key 1"))
    8169            4 :         );
    8170            4 :         assert_eq!(
    8171            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8172            4 :             Some(test_img("metadata inherited key 2"))
    8173            4 :         );
    8174            4 :         assert_eq!(
    8175            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8176            4 :             None
    8177            4 :         );
    8178            4 :         assert_eq!(
    8179            4 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8180            4 :             Some(test_img("metadata key overwrite 2b"))
    8181            4 :         );
    8182            4 :         assert_eq!(
    8183            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8184            4 :             Some(test_img("metadata key overwrite 2a"))
    8185            4 :         );
    8186            4 : 
    8187            4 :         // test vectored scan on parent timeline
    8188            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8189            4 :         let res = tline
    8190            4 :             .get_vectored_impl(
    8191            4 :                 KeySpace::single(Key::metadata_key_range()),
    8192            4 :                 lsn,
    8193            4 :                 &mut reconstruct_state,
    8194            4 :                 &ctx,
    8195            4 :             )
    8196            4 :             .await?;
    8197            4 : 
    8198            4 :         assert_eq!(
    8199            4 :             res.into_iter()
    8200           16 :                 .map(|(k, v)| (k, v.unwrap()))
    8201            4 :                 .collect::<Vec<_>>(),
    8202            4 :             vec![
    8203            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8204            4 :                 (
    8205            4 :                     base_inherited_key_overwrite,
    8206            4 :                     test_img("metadata key overwrite 1a")
    8207            4 :                 ),
    8208            4 :                 (base_key, test_img("metadata key 1")),
    8209            4 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8210            4 :             ]
    8211            4 :         );
    8212            4 : 
    8213            4 :         // test vectored scan on child timeline
    8214            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8215            4 :         let res = child
    8216            4 :             .get_vectored_impl(
    8217            4 :                 KeySpace::single(Key::metadata_key_range()),
    8218            4 :                 lsn,
    8219            4 :                 &mut reconstruct_state,
    8220            4 :                 &ctx,
    8221            4 :             )
    8222            4 :             .await?;
    8223            4 : 
    8224            4 :         assert_eq!(
    8225            4 :             res.into_iter()
    8226           20 :                 .map(|(k, v)| (k, v.unwrap()))
    8227            4 :                 .collect::<Vec<_>>(),
    8228            4 :             vec![
    8229            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8230            4 :                 (
    8231            4 :                     base_inherited_key_child,
    8232            4 :                     test_img("metadata inherited key 2")
    8233            4 :                 ),
    8234            4 :                 (
    8235            4 :                     base_inherited_key_overwrite,
    8236            4 :                     test_img("metadata key overwrite 2a")
    8237            4 :                 ),
    8238            4 :                 (base_key_child, test_img("metadata key 2")),
    8239            4 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8240            4 :             ]
    8241            4 :         );
    8242            4 : 
    8243            4 :         Ok(())
    8244            4 :     }
    8245              : 
    8246          112 :     async fn get_vectored_impl_wrapper(
    8247          112 :         tline: &Arc<Timeline>,
    8248          112 :         key: Key,
    8249          112 :         lsn: Lsn,
    8250          112 :         ctx: &RequestContext,
    8251          112 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8252          112 :         let io_concurrency =
    8253          112 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    8254          112 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8255          112 :         let mut res = tline
    8256          112 :             .get_vectored_impl(
    8257          112 :                 KeySpace::single(key..key.next()),
    8258          112 :                 lsn,
    8259          112 :                 &mut reconstruct_state,
    8260          112 :                 ctx,
    8261          112 :             )
    8262          112 :             .await?;
    8263          100 :         Ok(res.pop_last().map(|(k, v)| {
    8264           64 :             assert_eq!(k, key);
    8265           64 :             v.unwrap()
    8266          100 :         }))
    8267          112 :     }
    8268              : 
    8269              :     #[tokio::test]
    8270            4 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8271            4 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8272            4 :         let (tenant, ctx) = harness.load().await;
    8273            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8274            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8275            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8276            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8277            4 : 
    8278            4 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8279            4 :         // Lsn 0x30 key0, key3, no key1+key2
    8280            4 :         // Lsn 0x20 key1+key2 tomestones
    8281            4 :         // Lsn 0x10 key1 in image, key2 in delta
    8282            4 :         let tline = tenant
    8283            4 :             .create_test_timeline_with_layers(
    8284            4 :                 TIMELINE_ID,
    8285            4 :                 Lsn(0x10),
    8286            4 :                 DEFAULT_PG_VERSION,
    8287            4 :                 &ctx,
    8288            4 :                 Vec::new(), // in-memory layers
    8289            4 :                 // delta layers
    8290            4 :                 vec![
    8291            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8292            4 :                         Lsn(0x10)..Lsn(0x20),
    8293            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8294            4 :                     ),
    8295            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8296            4 :                         Lsn(0x20)..Lsn(0x30),
    8297            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8298            4 :                     ),
    8299            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8300            4 :                         Lsn(0x20)..Lsn(0x30),
    8301            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8302            4 :                     ),
    8303            4 :                 ],
    8304            4 :                 // image layers
    8305            4 :                 vec![
    8306            4 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8307            4 :                     (
    8308            4 :                         Lsn(0x30),
    8309            4 :                         vec![
    8310            4 :                             (key0, test_img("metadata key 0")),
    8311            4 :                             (key3, test_img("metadata key 3")),
    8312            4 :                         ],
    8313            4 :                     ),
    8314            4 :                 ],
    8315            4 :                 Lsn(0x30),
    8316            4 :             )
    8317            4 :             .await?;
    8318            4 : 
    8319            4 :         let lsn = Lsn(0x30);
    8320            4 :         let old_lsn = Lsn(0x20);
    8321            4 : 
    8322            4 :         assert_eq!(
    8323            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8324            4 :             Some(test_img("metadata key 0"))
    8325            4 :         );
    8326            4 :         assert_eq!(
    8327            4 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8328            4 :             None,
    8329            4 :         );
    8330            4 :         assert_eq!(
    8331            4 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8332            4 :             None,
    8333            4 :         );
    8334            4 :         assert_eq!(
    8335            4 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8336            4 :             Some(Bytes::new()),
    8337            4 :         );
    8338            4 :         assert_eq!(
    8339            4 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8340            4 :             Some(Bytes::new()),
    8341            4 :         );
    8342            4 :         assert_eq!(
    8343            4 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8344            4 :             Some(test_img("metadata key 3"))
    8345            4 :         );
    8346            4 : 
    8347            4 :         Ok(())
    8348            4 :     }
    8349              : 
    8350              :     #[tokio::test]
    8351            4 :     async fn test_metadata_tombstone_image_creation() {
    8352            4 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8353            4 :             .await
    8354            4 :             .unwrap();
    8355            4 :         let (tenant, ctx) = harness.load().await;
    8356            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8357            4 : 
    8358            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8359            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8360            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8361            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8362            4 : 
    8363            4 :         let tline = tenant
    8364            4 :             .create_test_timeline_with_layers(
    8365            4 :                 TIMELINE_ID,
    8366            4 :                 Lsn(0x10),
    8367            4 :                 DEFAULT_PG_VERSION,
    8368            4 :                 &ctx,
    8369            4 :                 Vec::new(), // in-memory layers
    8370            4 :                 // delta layers
    8371            4 :                 vec![
    8372            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8373            4 :                         Lsn(0x10)..Lsn(0x20),
    8374            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8375            4 :                     ),
    8376            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8377            4 :                         Lsn(0x20)..Lsn(0x30),
    8378            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8379            4 :                     ),
    8380            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8381            4 :                         Lsn(0x20)..Lsn(0x30),
    8382            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8383            4 :                     ),
    8384            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8385            4 :                         Lsn(0x30)..Lsn(0x40),
    8386            4 :                         vec![
    8387            4 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8388            4 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8389            4 :                         ],
    8390            4 :                     ),
    8391            4 :                 ],
    8392            4 :                 // image layers
    8393            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8394            4 :                 Lsn(0x40),
    8395            4 :             )
    8396            4 :             .await
    8397            4 :             .unwrap();
    8398            4 : 
    8399            4 :         let cancel = CancellationToken::new();
    8400            4 : 
    8401            4 :         tline
    8402            4 :             .compact(
    8403            4 :                 &cancel,
    8404            4 :                 {
    8405            4 :                     let mut flags = EnumSet::new();
    8406            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8407            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8408            4 :                     flags
    8409            4 :                 },
    8410            4 :                 &ctx,
    8411            4 :             )
    8412            4 :             .await
    8413            4 :             .unwrap();
    8414            4 : 
    8415            4 :         // Image layers are created at last_record_lsn
    8416            4 :         let images = tline
    8417            4 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8418            4 :             .await
    8419            4 :             .unwrap()
    8420            4 :             .into_iter()
    8421           36 :             .filter(|(k, _)| k.is_metadata_key())
    8422            4 :             .collect::<Vec<_>>();
    8423            4 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8424            4 :     }
    8425              : 
    8426              :     #[tokio::test]
    8427            4 :     async fn test_metadata_tombstone_empty_image_creation() {
    8428            4 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8429            4 :             .await
    8430            4 :             .unwrap();
    8431            4 :         let (tenant, ctx) = harness.load().await;
    8432            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8433            4 : 
    8434            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8435            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8436            4 : 
    8437            4 :         let tline = tenant
    8438            4 :             .create_test_timeline_with_layers(
    8439            4 :                 TIMELINE_ID,
    8440            4 :                 Lsn(0x10),
    8441            4 :                 DEFAULT_PG_VERSION,
    8442            4 :                 &ctx,
    8443            4 :                 Vec::new(), // in-memory layers
    8444            4 :                 // delta layers
    8445            4 :                 vec![
    8446            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8447            4 :                         Lsn(0x10)..Lsn(0x20),
    8448            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8449            4 :                     ),
    8450            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8451            4 :                         Lsn(0x20)..Lsn(0x30),
    8452            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8453            4 :                     ),
    8454            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8455            4 :                         Lsn(0x20)..Lsn(0x30),
    8456            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8457            4 :                     ),
    8458            4 :                 ],
    8459            4 :                 // image layers
    8460            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8461            4 :                 Lsn(0x30),
    8462            4 :             )
    8463            4 :             .await
    8464            4 :             .unwrap();
    8465            4 : 
    8466            4 :         let cancel = CancellationToken::new();
    8467            4 : 
    8468            4 :         tline
    8469            4 :             .compact(
    8470            4 :                 &cancel,
    8471            4 :                 {
    8472            4 :                     let mut flags = EnumSet::new();
    8473            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8474            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8475            4 :                     flags
    8476            4 :                 },
    8477            4 :                 &ctx,
    8478            4 :             )
    8479            4 :             .await
    8480            4 :             .unwrap();
    8481            4 : 
    8482            4 :         // Image layers are created at last_record_lsn
    8483            4 :         let images = tline
    8484            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8485            4 :             .await
    8486            4 :             .unwrap()
    8487            4 :             .into_iter()
    8488           28 :             .filter(|(k, _)| k.is_metadata_key())
    8489            4 :             .collect::<Vec<_>>();
    8490            4 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8491            4 :     }
    8492              : 
    8493              :     #[tokio::test]
    8494            4 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8495            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8496            4 :         let (tenant, ctx) = harness.load().await;
    8497            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8498            4 : 
    8499          204 :         fn get_key(id: u32) -> Key {
    8500          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8501          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8502          204 :             key.field6 = id;
    8503          204 :             key
    8504          204 :         }
    8505            4 : 
    8506            4 :         // We create
    8507            4 :         // - one bottom-most image layer,
    8508            4 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8509            4 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8510            4 :         // - a delta layer D3 above the horizon.
    8511            4 :         //
    8512            4 :         //                             | D3 |
    8513            4 :         //  | D1 |
    8514            4 :         // -|    |-- gc horizon -----------------
    8515            4 :         //  |    |                | D2 |
    8516            4 :         // --------- img layer ------------------
    8517            4 :         //
    8518            4 :         // What we should expact from this compaction is:
    8519            4 :         //                             | D3 |
    8520            4 :         //  | Part of D1 |
    8521            4 :         // --------- img layer with D1+D2 at GC horizon------------------
    8522            4 : 
    8523            4 :         // img layer at 0x10
    8524            4 :         let img_layer = (0..10)
    8525           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8526            4 :             .collect_vec();
    8527            4 : 
    8528            4 :         let delta1 = vec![
    8529            4 :             (
    8530            4 :                 get_key(1),
    8531            4 :                 Lsn(0x20),
    8532            4 :                 Value::Image(Bytes::from("value 1@0x20")),
    8533            4 :             ),
    8534            4 :             (
    8535            4 :                 get_key(2),
    8536            4 :                 Lsn(0x30),
    8537            4 :                 Value::Image(Bytes::from("value 2@0x30")),
    8538            4 :             ),
    8539            4 :             (
    8540            4 :                 get_key(3),
    8541            4 :                 Lsn(0x40),
    8542            4 :                 Value::Image(Bytes::from("value 3@0x40")),
    8543            4 :             ),
    8544            4 :         ];
    8545            4 :         let delta2 = vec![
    8546            4 :             (
    8547            4 :                 get_key(5),
    8548            4 :                 Lsn(0x20),
    8549            4 :                 Value::Image(Bytes::from("value 5@0x20")),
    8550            4 :             ),
    8551            4 :             (
    8552            4 :                 get_key(6),
    8553            4 :                 Lsn(0x20),
    8554            4 :                 Value::Image(Bytes::from("value 6@0x20")),
    8555            4 :             ),
    8556            4 :         ];
    8557            4 :         let delta3 = vec![
    8558            4 :             (
    8559            4 :                 get_key(8),
    8560            4 :                 Lsn(0x48),
    8561            4 :                 Value::Image(Bytes::from("value 8@0x48")),
    8562            4 :             ),
    8563            4 :             (
    8564            4 :                 get_key(9),
    8565            4 :                 Lsn(0x48),
    8566            4 :                 Value::Image(Bytes::from("value 9@0x48")),
    8567            4 :             ),
    8568            4 :         ];
    8569            4 : 
    8570            4 :         let tline = tenant
    8571            4 :             .create_test_timeline_with_layers(
    8572            4 :                 TIMELINE_ID,
    8573            4 :                 Lsn(0x10),
    8574            4 :                 DEFAULT_PG_VERSION,
    8575            4 :                 &ctx,
    8576            4 :                 Vec::new(), // in-memory layers
    8577            4 :                 vec![
    8578            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8579            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8580            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8581            4 :                 ], // delta layers
    8582            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8583            4 :                 Lsn(0x50),
    8584            4 :             )
    8585            4 :             .await?;
    8586            4 :         {
    8587            4 :             tline
    8588            4 :                 .applied_gc_cutoff_lsn
    8589            4 :                 .lock_for_write()
    8590            4 :                 .store_and_unlock(Lsn(0x30))
    8591            4 :                 .wait()
    8592            4 :                 .await;
    8593            4 :             // Update GC info
    8594            4 :             let mut guard = tline.gc_info.write().unwrap();
    8595            4 :             guard.cutoffs.time = Lsn(0x30);
    8596            4 :             guard.cutoffs.space = Lsn(0x30);
    8597            4 :         }
    8598            4 : 
    8599            4 :         let expected_result = [
    8600            4 :             Bytes::from_static(b"value 0@0x10"),
    8601            4 :             Bytes::from_static(b"value 1@0x20"),
    8602            4 :             Bytes::from_static(b"value 2@0x30"),
    8603            4 :             Bytes::from_static(b"value 3@0x40"),
    8604            4 :             Bytes::from_static(b"value 4@0x10"),
    8605            4 :             Bytes::from_static(b"value 5@0x20"),
    8606            4 :             Bytes::from_static(b"value 6@0x20"),
    8607            4 :             Bytes::from_static(b"value 7@0x10"),
    8608            4 :             Bytes::from_static(b"value 8@0x48"),
    8609            4 :             Bytes::from_static(b"value 9@0x48"),
    8610            4 :         ];
    8611            4 : 
    8612           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8613           40 :             assert_eq!(
    8614           40 :                 tline
    8615           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8616           40 :                     .await
    8617           40 :                     .unwrap(),
    8618            4 :                 expected
    8619            4 :             );
    8620            4 :         }
    8621            4 : 
    8622            4 :         let cancel = CancellationToken::new();
    8623            4 :         tline
    8624            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8625            4 :             .await
    8626            4 :             .unwrap();
    8627            4 : 
    8628           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8629           40 :             assert_eq!(
    8630           40 :                 tline
    8631           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8632           40 :                     .await
    8633           40 :                     .unwrap(),
    8634            4 :                 expected
    8635            4 :             );
    8636            4 :         }
    8637            4 : 
    8638            4 :         // Check if the image layer at the GC horizon contains exactly what we want
    8639            4 :         let image_at_gc_horizon = tline
    8640            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8641            4 :             .await
    8642            4 :             .unwrap()
    8643            4 :             .into_iter()
    8644           68 :             .filter(|(k, _)| k.is_metadata_key())
    8645            4 :             .collect::<Vec<_>>();
    8646            4 : 
    8647            4 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8648            4 :         let expected_result = [
    8649            4 :             Bytes::from_static(b"value 0@0x10"),
    8650            4 :             Bytes::from_static(b"value 1@0x20"),
    8651            4 :             Bytes::from_static(b"value 2@0x30"),
    8652            4 :             Bytes::from_static(b"value 3@0x10"),
    8653            4 :             Bytes::from_static(b"value 4@0x10"),
    8654            4 :             Bytes::from_static(b"value 5@0x20"),
    8655            4 :             Bytes::from_static(b"value 6@0x20"),
    8656            4 :             Bytes::from_static(b"value 7@0x10"),
    8657            4 :             Bytes::from_static(b"value 8@0x10"),
    8658            4 :             Bytes::from_static(b"value 9@0x10"),
    8659            4 :         ];
    8660           44 :         for idx in 0..10 {
    8661           40 :             assert_eq!(
    8662           40 :                 image_at_gc_horizon[idx],
    8663           40 :                 (get_key(idx as u32), expected_result[idx].clone())
    8664           40 :             );
    8665            4 :         }
    8666            4 : 
    8667            4 :         // Check if old layers are removed / new layers have the expected LSN
    8668            4 :         let all_layers = inspect_and_sort(&tline, None).await;
    8669            4 :         assert_eq!(
    8670            4 :             all_layers,
    8671            4 :             vec![
    8672            4 :                 // Image layer at GC horizon
    8673            4 :                 PersistentLayerKey {
    8674            4 :                     key_range: Key::MIN..Key::MAX,
    8675            4 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8676            4 :                     is_delta: false
    8677            4 :                 },
    8678            4 :                 // The delta layer below the horizon
    8679            4 :                 PersistentLayerKey {
    8680            4 :                     key_range: get_key(3)..get_key(4),
    8681            4 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8682            4 :                     is_delta: true
    8683            4 :                 },
    8684            4 :                 // The delta3 layer that should not be picked for the compaction
    8685            4 :                 PersistentLayerKey {
    8686            4 :                     key_range: get_key(8)..get_key(10),
    8687            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8688            4 :                     is_delta: true
    8689            4 :                 }
    8690            4 :             ]
    8691            4 :         );
    8692            4 : 
    8693            4 :         // increase GC horizon and compact again
    8694            4 :         {
    8695            4 :             tline
    8696            4 :                 .applied_gc_cutoff_lsn
    8697            4 :                 .lock_for_write()
    8698            4 :                 .store_and_unlock(Lsn(0x40))
    8699            4 :                 .wait()
    8700            4 :                 .await;
    8701            4 :             // Update GC info
    8702            4 :             let mut guard = tline.gc_info.write().unwrap();
    8703            4 :             guard.cutoffs.time = Lsn(0x40);
    8704            4 :             guard.cutoffs.space = Lsn(0x40);
    8705            4 :         }
    8706            4 :         tline
    8707            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8708            4 :             .await
    8709            4 :             .unwrap();
    8710            4 : 
    8711            4 :         Ok(())
    8712            4 :     }
    8713              : 
    8714              :     #[cfg(feature = "testing")]
    8715              :     #[tokio::test]
    8716            4 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8717            4 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8718            4 :         let (tenant, ctx) = harness.load().await;
    8719            4 : 
    8720           48 :         fn get_key(id: u32) -> Key {
    8721           48 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8722           48 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8723           48 :             key.field6 = id;
    8724           48 :             key
    8725           48 :         }
    8726            4 : 
    8727            4 :         let delta1 = vec![
    8728            4 :             (
    8729            4 :                 get_key(1),
    8730            4 :                 Lsn(0x20),
    8731            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8732            4 :             ),
    8733            4 :             (
    8734            4 :                 get_key(1),
    8735            4 :                 Lsn(0x30),
    8736            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8737            4 :             ),
    8738            4 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8739            4 :             (
    8740            4 :                 get_key(2),
    8741            4 :                 Lsn(0x20),
    8742            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8743            4 :             ),
    8744            4 :             (
    8745            4 :                 get_key(2),
    8746            4 :                 Lsn(0x30),
    8747            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8748            4 :             ),
    8749            4 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8750            4 :             (
    8751            4 :                 get_key(3),
    8752            4 :                 Lsn(0x20),
    8753            4 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8754            4 :             ),
    8755            4 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8756            4 :             (
    8757            4 :                 get_key(4),
    8758            4 :                 Lsn(0x20),
    8759            4 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8760            4 :             ),
    8761            4 :         ];
    8762            4 :         let image1 = vec![(get_key(1), "0x10".into())];
    8763            4 : 
    8764            4 :         let tline = tenant
    8765            4 :             .create_test_timeline_with_layers(
    8766            4 :                 TIMELINE_ID,
    8767            4 :                 Lsn(0x10),
    8768            4 :                 DEFAULT_PG_VERSION,
    8769            4 :                 &ctx,
    8770            4 :                 Vec::new(), // in-memory layers
    8771            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8772            4 :                     Lsn(0x10)..Lsn(0x40),
    8773            4 :                     delta1,
    8774            4 :                 )], // delta layers
    8775            4 :                 vec![(Lsn(0x10), image1)], // image layers
    8776            4 :                 Lsn(0x50),
    8777            4 :             )
    8778            4 :             .await?;
    8779            4 : 
    8780            4 :         assert_eq!(
    8781            4 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8782            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8783            4 :         );
    8784            4 :         assert_eq!(
    8785            4 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8786            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8787            4 :         );
    8788            4 : 
    8789            4 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8790            4 : 
    8791            4 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8792            4 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8793            4 : 
    8794            4 :         Ok(())
    8795            4 :     }
    8796              : 
    8797              :     #[tokio::test(start_paused = true)]
    8798            4 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8799            4 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8800            4 :             .await
    8801            4 :             .unwrap()
    8802            4 :             .load()
    8803            4 :             .await;
    8804            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8805            4 :         // initial transition into AttachedSingle.
    8806            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8807            4 :         tokio::time::resume();
    8808            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8809            4 : 
    8810            4 :         let end_lsn = Lsn(0x100);
    8811            4 :         let image_layers = (0x20..=0x90)
    8812            4 :             .step_by(0x10)
    8813           32 :             .map(|n| {
    8814           32 :                 (
    8815           32 :                     Lsn(n),
    8816           32 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8817           32 :                 )
    8818           32 :             })
    8819            4 :             .collect();
    8820            4 : 
    8821            4 :         let timeline = tenant
    8822            4 :             .create_test_timeline_with_layers(
    8823            4 :                 TIMELINE_ID,
    8824            4 :                 Lsn(0x10),
    8825            4 :                 DEFAULT_PG_VERSION,
    8826            4 :                 &ctx,
    8827            4 :                 Vec::new(), // in-memory layers
    8828            4 :                 Vec::new(),
    8829            4 :                 image_layers,
    8830            4 :                 end_lsn,
    8831            4 :             )
    8832            4 :             .await?;
    8833            4 : 
    8834            4 :         let leased_lsns = [0x30, 0x50, 0x70];
    8835            4 :         let mut leases = Vec::new();
    8836           12 :         leased_lsns.iter().for_each(|n| {
    8837           12 :             leases.push(
    8838           12 :                 timeline
    8839           12 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8840           12 :                     .expect("lease request should succeed"),
    8841           12 :             );
    8842           12 :         });
    8843            4 : 
    8844            4 :         let updated_lease_0 = timeline
    8845            4 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8846            4 :             .expect("lease renewal should succeed");
    8847            4 :         assert_eq!(
    8848            4 :             updated_lease_0.valid_until, leases[0].valid_until,
    8849            4 :             " Renewing with shorter lease should not change the lease."
    8850            4 :         );
    8851            4 : 
    8852            4 :         let updated_lease_1 = timeline
    8853            4 :             .renew_lsn_lease(
    8854            4 :                 Lsn(leased_lsns[1]),
    8855            4 :                 timeline.get_lsn_lease_length() * 2,
    8856            4 :                 &ctx,
    8857            4 :             )
    8858            4 :             .expect("lease renewal should succeed");
    8859            4 :         assert!(
    8860            4 :             updated_lease_1.valid_until > leases[1].valid_until,
    8861            4 :             "Renewing with a long lease should renew lease with later expiration time."
    8862            4 :         );
    8863            4 : 
    8864            4 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8865            4 :         info!(
    8866            4 :             "applied_gc_cutoff_lsn: {}",
    8867            0 :             *timeline.get_applied_gc_cutoff_lsn()
    8868            4 :         );
    8869            4 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8870            4 : 
    8871            4 :         let res = tenant
    8872            4 :             .gc_iteration(
    8873            4 :                 Some(TIMELINE_ID),
    8874            4 :                 0,
    8875            4 :                 Duration::ZERO,
    8876            4 :                 &CancellationToken::new(),
    8877            4 :                 &ctx,
    8878            4 :             )
    8879            4 :             .await
    8880            4 :             .unwrap();
    8881            4 : 
    8882            4 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8883            4 :         // 0/10: initdb layer
    8884            4 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8885            4 :         assert_eq!(res.layers_needed_by_leases, 7);
    8886            4 :         // Keeping 0/90 b/c it is the latest layer.
    8887            4 :         assert_eq!(res.layers_not_updated, 1);
    8888            4 :         // Removed 0/80.
    8889            4 :         assert_eq!(res.layers_removed, 1);
    8890            4 : 
    8891            4 :         // Make lease on a already GC-ed LSN.
    8892            4 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8893            4 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    8894            4 :         timeline
    8895            4 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8896            4 :             .expect_err("lease request on GC-ed LSN should fail");
    8897            4 : 
    8898            4 :         // Should still be able to renew a currently valid lease
    8899            4 :         // Assumption: original lease to is still valid for 0/50.
    8900            4 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8901            4 :         timeline
    8902            4 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8903            4 :             .expect("lease renewal with validation should succeed");
    8904            4 : 
    8905            4 :         Ok(())
    8906            4 :     }
    8907              : 
    8908              :     #[cfg(feature = "testing")]
    8909              :     #[tokio::test]
    8910            4 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8911            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8912            4 :             "test_simple_bottom_most_compaction_deltas_1",
    8913            4 :             false,
    8914            4 :         )
    8915            4 :         .await
    8916            4 :     }
    8917              : 
    8918              :     #[cfg(feature = "testing")]
    8919              :     #[tokio::test]
    8920            4 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8921            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8922            4 :             "test_simple_bottom_most_compaction_deltas_2",
    8923            4 :             true,
    8924            4 :         )
    8925            4 :         .await
    8926            4 :     }
    8927              : 
    8928              :     #[cfg(feature = "testing")]
    8929            8 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8930            8 :         test_name: &'static str,
    8931            8 :         use_delta_bottom_layer: bool,
    8932            8 :     ) -> anyhow::Result<()> {
    8933            8 :         let harness = TenantHarness::create(test_name).await?;
    8934            8 :         let (tenant, ctx) = harness.load().await;
    8935              : 
    8936          552 :         fn get_key(id: u32) -> Key {
    8937          552 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8938          552 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8939          552 :             key.field6 = id;
    8940          552 :             key
    8941          552 :         }
    8942              : 
    8943              :         // We create
    8944              :         // - one bottom-most image layer,
    8945              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8946              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8947              :         // - a delta layer D3 above the horizon.
    8948              :         //
    8949              :         //                             | D3 |
    8950              :         //  | D1 |
    8951              :         // -|    |-- gc horizon -----------------
    8952              :         //  |    |                | D2 |
    8953              :         // --------- img layer ------------------
    8954              :         //
    8955              :         // What we should expact from this compaction is:
    8956              :         //                             | D3 |
    8957              :         //  | Part of D1 |
    8958              :         // --------- img layer with D1+D2 at GC horizon------------------
    8959              : 
    8960              :         // img layer at 0x10
    8961            8 :         let img_layer = (0..10)
    8962           80 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8963            8 :             .collect_vec();
    8964            8 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8965            8 :         let delta4 = (0..10)
    8966           80 :             .map(|id| {
    8967           80 :                 (
    8968           80 :                     get_key(id),
    8969           80 :                     Lsn(0x08),
    8970           80 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8971           80 :                 )
    8972           80 :             })
    8973            8 :             .collect_vec();
    8974            8 : 
    8975            8 :         let delta1 = vec![
    8976            8 :             (
    8977            8 :                 get_key(1),
    8978            8 :                 Lsn(0x20),
    8979            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8980            8 :             ),
    8981            8 :             (
    8982            8 :                 get_key(2),
    8983            8 :                 Lsn(0x30),
    8984            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8985            8 :             ),
    8986            8 :             (
    8987            8 :                 get_key(3),
    8988            8 :                 Lsn(0x28),
    8989            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8990            8 :             ),
    8991            8 :             (
    8992            8 :                 get_key(3),
    8993            8 :                 Lsn(0x30),
    8994            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8995            8 :             ),
    8996            8 :             (
    8997            8 :                 get_key(3),
    8998            8 :                 Lsn(0x40),
    8999            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9000            8 :             ),
    9001            8 :         ];
    9002            8 :         let delta2 = vec![
    9003            8 :             (
    9004            8 :                 get_key(5),
    9005            8 :                 Lsn(0x20),
    9006            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9007            8 :             ),
    9008            8 :             (
    9009            8 :                 get_key(6),
    9010            8 :                 Lsn(0x20),
    9011            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9012            8 :             ),
    9013            8 :         ];
    9014            8 :         let delta3 = vec![
    9015            8 :             (
    9016            8 :                 get_key(8),
    9017            8 :                 Lsn(0x48),
    9018            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9019            8 :             ),
    9020            8 :             (
    9021            8 :                 get_key(9),
    9022            8 :                 Lsn(0x48),
    9023            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9024            8 :             ),
    9025            8 :         ];
    9026              : 
    9027            8 :         let tline = if use_delta_bottom_layer {
    9028            4 :             tenant
    9029            4 :                 .create_test_timeline_with_layers(
    9030            4 :                     TIMELINE_ID,
    9031            4 :                     Lsn(0x08),
    9032            4 :                     DEFAULT_PG_VERSION,
    9033            4 :                     &ctx,
    9034            4 :                     Vec::new(), // in-memory layers
    9035            4 :                     vec![
    9036            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9037            4 :                             Lsn(0x08)..Lsn(0x10),
    9038            4 :                             delta4,
    9039            4 :                         ),
    9040            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9041            4 :                             Lsn(0x20)..Lsn(0x48),
    9042            4 :                             delta1,
    9043            4 :                         ),
    9044            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9045            4 :                             Lsn(0x20)..Lsn(0x48),
    9046            4 :                             delta2,
    9047            4 :                         ),
    9048            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9049            4 :                             Lsn(0x48)..Lsn(0x50),
    9050            4 :                             delta3,
    9051            4 :                         ),
    9052            4 :                     ], // delta layers
    9053            4 :                     vec![],     // image layers
    9054            4 :                     Lsn(0x50),
    9055            4 :                 )
    9056            4 :                 .await?
    9057              :         } else {
    9058            4 :             tenant
    9059            4 :                 .create_test_timeline_with_layers(
    9060            4 :                     TIMELINE_ID,
    9061            4 :                     Lsn(0x10),
    9062            4 :                     DEFAULT_PG_VERSION,
    9063            4 :                     &ctx,
    9064            4 :                     Vec::new(), // in-memory layers
    9065            4 :                     vec![
    9066            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9067            4 :                             Lsn(0x10)..Lsn(0x48),
    9068            4 :                             delta1,
    9069            4 :                         ),
    9070            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9071            4 :                             Lsn(0x10)..Lsn(0x48),
    9072            4 :                             delta2,
    9073            4 :                         ),
    9074            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9075            4 :                             Lsn(0x48)..Lsn(0x50),
    9076            4 :                             delta3,
    9077            4 :                         ),
    9078            4 :                     ], // delta layers
    9079            4 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9080            4 :                     Lsn(0x50),
    9081            4 :                 )
    9082            4 :                 .await?
    9083              :         };
    9084              :         {
    9085            8 :             tline
    9086            8 :                 .applied_gc_cutoff_lsn
    9087            8 :                 .lock_for_write()
    9088            8 :                 .store_and_unlock(Lsn(0x30))
    9089            8 :                 .wait()
    9090            8 :                 .await;
    9091              :             // Update GC info
    9092            8 :             let mut guard = tline.gc_info.write().unwrap();
    9093            8 :             *guard = GcInfo {
    9094            8 :                 retain_lsns: vec![],
    9095            8 :                 cutoffs: GcCutoffs {
    9096            8 :                     time: Lsn(0x30),
    9097            8 :                     space: Lsn(0x30),
    9098            8 :                 },
    9099            8 :                 leases: Default::default(),
    9100            8 :                 within_ancestor_pitr: false,
    9101            8 :             };
    9102            8 :         }
    9103            8 : 
    9104            8 :         let expected_result = [
    9105            8 :             Bytes::from_static(b"value 0@0x10"),
    9106            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9107            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9108            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9109            8 :             Bytes::from_static(b"value 4@0x10"),
    9110            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9111            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9112            8 :             Bytes::from_static(b"value 7@0x10"),
    9113            8 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9114            8 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9115            8 :         ];
    9116            8 : 
    9117            8 :         let expected_result_at_gc_horizon = [
    9118            8 :             Bytes::from_static(b"value 0@0x10"),
    9119            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9120            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9121            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9122            8 :             Bytes::from_static(b"value 4@0x10"),
    9123            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9124            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9125            8 :             Bytes::from_static(b"value 7@0x10"),
    9126            8 :             Bytes::from_static(b"value 8@0x10"),
    9127            8 :             Bytes::from_static(b"value 9@0x10"),
    9128            8 :         ];
    9129              : 
    9130           88 :         for idx in 0..10 {
    9131           80 :             assert_eq!(
    9132           80 :                 tline
    9133           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9134           80 :                     .await
    9135           80 :                     .unwrap(),
    9136           80 :                 &expected_result[idx]
    9137              :             );
    9138           80 :             assert_eq!(
    9139           80 :                 tline
    9140           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9141           80 :                     .await
    9142           80 :                     .unwrap(),
    9143           80 :                 &expected_result_at_gc_horizon[idx]
    9144              :             );
    9145              :         }
    9146              : 
    9147            8 :         let cancel = CancellationToken::new();
    9148            8 :         tline
    9149            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9150            8 :             .await
    9151            8 :             .unwrap();
    9152              : 
    9153           88 :         for idx in 0..10 {
    9154           80 :             assert_eq!(
    9155           80 :                 tline
    9156           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9157           80 :                     .await
    9158           80 :                     .unwrap(),
    9159           80 :                 &expected_result[idx]
    9160              :             );
    9161           80 :             assert_eq!(
    9162           80 :                 tline
    9163           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9164           80 :                     .await
    9165           80 :                     .unwrap(),
    9166           80 :                 &expected_result_at_gc_horizon[idx]
    9167              :             );
    9168              :         }
    9169              : 
    9170              :         // increase GC horizon and compact again
    9171              :         {
    9172            8 :             tline
    9173            8 :                 .applied_gc_cutoff_lsn
    9174            8 :                 .lock_for_write()
    9175            8 :                 .store_and_unlock(Lsn(0x40))
    9176            8 :                 .wait()
    9177            8 :                 .await;
    9178              :             // Update GC info
    9179            8 :             let mut guard = tline.gc_info.write().unwrap();
    9180            8 :             guard.cutoffs.time = Lsn(0x40);
    9181            8 :             guard.cutoffs.space = Lsn(0x40);
    9182            8 :         }
    9183            8 :         tline
    9184            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9185            8 :             .await
    9186            8 :             .unwrap();
    9187            8 : 
    9188            8 :         Ok(())
    9189            8 :     }
    9190              : 
    9191              :     #[cfg(feature = "testing")]
    9192              :     #[tokio::test]
    9193            4 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9194            4 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9195            4 :         let (tenant, ctx) = harness.load().await;
    9196            4 :         let tline = tenant
    9197            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9198            4 :             .await?;
    9199            4 :         tline.force_advance_lsn(Lsn(0x70));
    9200            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9201            4 :         let history = vec![
    9202            4 :             (
    9203            4 :                 key,
    9204            4 :                 Lsn(0x10),
    9205            4 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9206            4 :             ),
    9207            4 :             (
    9208            4 :                 key,
    9209            4 :                 Lsn(0x20),
    9210            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9211            4 :             ),
    9212            4 :             (
    9213            4 :                 key,
    9214            4 :                 Lsn(0x30),
    9215            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9216            4 :             ),
    9217            4 :             (
    9218            4 :                 key,
    9219            4 :                 Lsn(0x40),
    9220            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9221            4 :             ),
    9222            4 :             (
    9223            4 :                 key,
    9224            4 :                 Lsn(0x50),
    9225            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9226            4 :             ),
    9227            4 :             (
    9228            4 :                 key,
    9229            4 :                 Lsn(0x60),
    9230            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9231            4 :             ),
    9232            4 :             (
    9233            4 :                 key,
    9234            4 :                 Lsn(0x70),
    9235            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9236            4 :             ),
    9237            4 :             (
    9238            4 :                 key,
    9239            4 :                 Lsn(0x80),
    9240            4 :                 Value::Image(Bytes::copy_from_slice(
    9241            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9242            4 :                 )),
    9243            4 :             ),
    9244            4 :             (
    9245            4 :                 key,
    9246            4 :                 Lsn(0x90),
    9247            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9248            4 :             ),
    9249            4 :         ];
    9250            4 :         let res = tline
    9251            4 :             .generate_key_retention(
    9252            4 :                 key,
    9253            4 :                 &history,
    9254            4 :                 Lsn(0x60),
    9255            4 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9256            4 :                 3,
    9257            4 :                 None,
    9258            4 :             )
    9259            4 :             .await
    9260            4 :             .unwrap();
    9261            4 :         let expected_res = KeyHistoryRetention {
    9262            4 :             below_horizon: vec![
    9263            4 :                 (
    9264            4 :                     Lsn(0x20),
    9265            4 :                     KeyLogAtLsn(vec![(
    9266            4 :                         Lsn(0x20),
    9267            4 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9268            4 :                     )]),
    9269            4 :                 ),
    9270            4 :                 (
    9271            4 :                     Lsn(0x40),
    9272            4 :                     KeyLogAtLsn(vec![
    9273            4 :                         (
    9274            4 :                             Lsn(0x30),
    9275            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9276            4 :                         ),
    9277            4 :                         (
    9278            4 :                             Lsn(0x40),
    9279            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9280            4 :                         ),
    9281            4 :                     ]),
    9282            4 :                 ),
    9283            4 :                 (
    9284            4 :                     Lsn(0x50),
    9285            4 :                     KeyLogAtLsn(vec![(
    9286            4 :                         Lsn(0x50),
    9287            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9288            4 :                     )]),
    9289            4 :                 ),
    9290            4 :                 (
    9291            4 :                     Lsn(0x60),
    9292            4 :                     KeyLogAtLsn(vec![(
    9293            4 :                         Lsn(0x60),
    9294            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9295            4 :                     )]),
    9296            4 :                 ),
    9297            4 :             ],
    9298            4 :             above_horizon: KeyLogAtLsn(vec![
    9299            4 :                 (
    9300            4 :                     Lsn(0x70),
    9301            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9302            4 :                 ),
    9303            4 :                 (
    9304            4 :                     Lsn(0x80),
    9305            4 :                     Value::Image(Bytes::copy_from_slice(
    9306            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9307            4 :                     )),
    9308            4 :                 ),
    9309            4 :                 (
    9310            4 :                     Lsn(0x90),
    9311            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9312            4 :                 ),
    9313            4 :             ]),
    9314            4 :         };
    9315            4 :         assert_eq!(res, expected_res);
    9316            4 : 
    9317            4 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9318            4 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9319            4 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9320            4 :         // For example, we have
    9321            4 :         // ```plain
    9322            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9323            4 :         // ```
    9324            4 :         // Now the GC horizon moves up, and we have
    9325            4 :         // ```plain
    9326            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9327            4 :         // ```
    9328            4 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9329            4 :         // We will end up with
    9330            4 :         // ```plain
    9331            4 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9332            4 :         // ```
    9333            4 :         // Now we run the GC-compaction, and this key does not have a full history.
    9334            4 :         // We should be able to handle this partial history and drop everything before the
    9335            4 :         // gc_horizon image.
    9336            4 : 
    9337            4 :         let history = vec![
    9338            4 :             (
    9339            4 :                 key,
    9340            4 :                 Lsn(0x20),
    9341            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9342            4 :             ),
    9343            4 :             (
    9344            4 :                 key,
    9345            4 :                 Lsn(0x30),
    9346            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9347            4 :             ),
    9348            4 :             (
    9349            4 :                 key,
    9350            4 :                 Lsn(0x40),
    9351            4 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9352            4 :             ),
    9353            4 :             (
    9354            4 :                 key,
    9355            4 :                 Lsn(0x50),
    9356            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9357            4 :             ),
    9358            4 :             (
    9359            4 :                 key,
    9360            4 :                 Lsn(0x60),
    9361            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9362            4 :             ),
    9363            4 :             (
    9364            4 :                 key,
    9365            4 :                 Lsn(0x70),
    9366            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9367            4 :             ),
    9368            4 :             (
    9369            4 :                 key,
    9370            4 :                 Lsn(0x80),
    9371            4 :                 Value::Image(Bytes::copy_from_slice(
    9372            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9373            4 :                 )),
    9374            4 :             ),
    9375            4 :             (
    9376            4 :                 key,
    9377            4 :                 Lsn(0x90),
    9378            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9379            4 :             ),
    9380            4 :         ];
    9381            4 :         let res = tline
    9382            4 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    9383            4 :             .await
    9384            4 :             .unwrap();
    9385            4 :         let expected_res = KeyHistoryRetention {
    9386            4 :             below_horizon: vec![
    9387            4 :                 (
    9388            4 :                     Lsn(0x40),
    9389            4 :                     KeyLogAtLsn(vec![(
    9390            4 :                         Lsn(0x40),
    9391            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9392            4 :                     )]),
    9393            4 :                 ),
    9394            4 :                 (
    9395            4 :                     Lsn(0x50),
    9396            4 :                     KeyLogAtLsn(vec![(
    9397            4 :                         Lsn(0x50),
    9398            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9399            4 :                     )]),
    9400            4 :                 ),
    9401            4 :                 (
    9402            4 :                     Lsn(0x60),
    9403            4 :                     KeyLogAtLsn(vec![(
    9404            4 :                         Lsn(0x60),
    9405            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9406            4 :                     )]),
    9407            4 :                 ),
    9408            4 :             ],
    9409            4 :             above_horizon: KeyLogAtLsn(vec![
    9410            4 :                 (
    9411            4 :                     Lsn(0x70),
    9412            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9413            4 :                 ),
    9414            4 :                 (
    9415            4 :                     Lsn(0x80),
    9416            4 :                     Value::Image(Bytes::copy_from_slice(
    9417            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9418            4 :                     )),
    9419            4 :                 ),
    9420            4 :                 (
    9421            4 :                     Lsn(0x90),
    9422            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9423            4 :                 ),
    9424            4 :             ]),
    9425            4 :         };
    9426            4 :         assert_eq!(res, expected_res);
    9427            4 : 
    9428            4 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9429            4 :         // the ancestor image in the test case.
    9430            4 : 
    9431            4 :         let history = vec![
    9432            4 :             (
    9433            4 :                 key,
    9434            4 :                 Lsn(0x20),
    9435            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9436            4 :             ),
    9437            4 :             (
    9438            4 :                 key,
    9439            4 :                 Lsn(0x30),
    9440            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9441            4 :             ),
    9442            4 :             (
    9443            4 :                 key,
    9444            4 :                 Lsn(0x40),
    9445            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9446            4 :             ),
    9447            4 :             (
    9448            4 :                 key,
    9449            4 :                 Lsn(0x70),
    9450            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9451            4 :             ),
    9452            4 :         ];
    9453            4 :         let res = tline
    9454            4 :             .generate_key_retention(
    9455            4 :                 key,
    9456            4 :                 &history,
    9457            4 :                 Lsn(0x60),
    9458            4 :                 &[],
    9459            4 :                 3,
    9460            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9461            4 :             )
    9462            4 :             .await
    9463            4 :             .unwrap();
    9464            4 :         let expected_res = KeyHistoryRetention {
    9465            4 :             below_horizon: vec![(
    9466            4 :                 Lsn(0x60),
    9467            4 :                 KeyLogAtLsn(vec![(
    9468            4 :                     Lsn(0x60),
    9469            4 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9470            4 :                 )]),
    9471            4 :             )],
    9472            4 :             above_horizon: KeyLogAtLsn(vec![(
    9473            4 :                 Lsn(0x70),
    9474            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9475            4 :             )]),
    9476            4 :         };
    9477            4 :         assert_eq!(res, expected_res);
    9478            4 : 
    9479            4 :         let history = vec![
    9480            4 :             (
    9481            4 :                 key,
    9482            4 :                 Lsn(0x20),
    9483            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9484            4 :             ),
    9485            4 :             (
    9486            4 :                 key,
    9487            4 :                 Lsn(0x40),
    9488            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9489            4 :             ),
    9490            4 :             (
    9491            4 :                 key,
    9492            4 :                 Lsn(0x60),
    9493            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9494            4 :             ),
    9495            4 :             (
    9496            4 :                 key,
    9497            4 :                 Lsn(0x70),
    9498            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9499            4 :             ),
    9500            4 :         ];
    9501            4 :         let res = tline
    9502            4 :             .generate_key_retention(
    9503            4 :                 key,
    9504            4 :                 &history,
    9505            4 :                 Lsn(0x60),
    9506            4 :                 &[Lsn(0x30)],
    9507            4 :                 3,
    9508            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9509            4 :             )
    9510            4 :             .await
    9511            4 :             .unwrap();
    9512            4 :         let expected_res = KeyHistoryRetention {
    9513            4 :             below_horizon: vec![
    9514            4 :                 (
    9515            4 :                     Lsn(0x30),
    9516            4 :                     KeyLogAtLsn(vec![(
    9517            4 :                         Lsn(0x20),
    9518            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9519            4 :                     )]),
    9520            4 :                 ),
    9521            4 :                 (
    9522            4 :                     Lsn(0x60),
    9523            4 :                     KeyLogAtLsn(vec![(
    9524            4 :                         Lsn(0x60),
    9525            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9526            4 :                     )]),
    9527            4 :                 ),
    9528            4 :             ],
    9529            4 :             above_horizon: KeyLogAtLsn(vec![(
    9530            4 :                 Lsn(0x70),
    9531            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9532            4 :             )]),
    9533            4 :         };
    9534            4 :         assert_eq!(res, expected_res);
    9535            4 : 
    9536            4 :         Ok(())
    9537            4 :     }
    9538              : 
    9539              :     #[cfg(feature = "testing")]
    9540              :     #[tokio::test]
    9541            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9542            4 :         let harness =
    9543            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9544            4 :         let (tenant, ctx) = harness.load().await;
    9545            4 : 
    9546         1036 :         fn get_key(id: u32) -> Key {
    9547         1036 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9548         1036 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9549         1036 :             key.field6 = id;
    9550         1036 :             key
    9551         1036 :         }
    9552            4 : 
    9553            4 :         let img_layer = (0..10)
    9554           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9555            4 :             .collect_vec();
    9556            4 : 
    9557            4 :         let delta1 = vec![
    9558            4 :             (
    9559            4 :                 get_key(1),
    9560            4 :                 Lsn(0x20),
    9561            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9562            4 :             ),
    9563            4 :             (
    9564            4 :                 get_key(2),
    9565            4 :                 Lsn(0x30),
    9566            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9567            4 :             ),
    9568            4 :             (
    9569            4 :                 get_key(3),
    9570            4 :                 Lsn(0x28),
    9571            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9572            4 :             ),
    9573            4 :             (
    9574            4 :                 get_key(3),
    9575            4 :                 Lsn(0x30),
    9576            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9577            4 :             ),
    9578            4 :             (
    9579            4 :                 get_key(3),
    9580            4 :                 Lsn(0x40),
    9581            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9582            4 :             ),
    9583            4 :         ];
    9584            4 :         let delta2 = vec![
    9585            4 :             (
    9586            4 :                 get_key(5),
    9587            4 :                 Lsn(0x20),
    9588            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9589            4 :             ),
    9590            4 :             (
    9591            4 :                 get_key(6),
    9592            4 :                 Lsn(0x20),
    9593            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9594            4 :             ),
    9595            4 :         ];
    9596            4 :         let delta3 = vec![
    9597            4 :             (
    9598            4 :                 get_key(8),
    9599            4 :                 Lsn(0x48),
    9600            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9601            4 :             ),
    9602            4 :             (
    9603            4 :                 get_key(9),
    9604            4 :                 Lsn(0x48),
    9605            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9606            4 :             ),
    9607            4 :         ];
    9608            4 : 
    9609            4 :         let tline = tenant
    9610            4 :             .create_test_timeline_with_layers(
    9611            4 :                 TIMELINE_ID,
    9612            4 :                 Lsn(0x10),
    9613            4 :                 DEFAULT_PG_VERSION,
    9614            4 :                 &ctx,
    9615            4 :                 Vec::new(), // in-memory layers
    9616            4 :                 vec![
    9617            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9618            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9619            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9620            4 :                 ], // delta layers
    9621            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9622            4 :                 Lsn(0x50),
    9623            4 :             )
    9624            4 :             .await?;
    9625            4 :         {
    9626            4 :             tline
    9627            4 :                 .applied_gc_cutoff_lsn
    9628            4 :                 .lock_for_write()
    9629            4 :                 .store_and_unlock(Lsn(0x30))
    9630            4 :                 .wait()
    9631            4 :                 .await;
    9632            4 :             // Update GC info
    9633            4 :             let mut guard = tline.gc_info.write().unwrap();
    9634            4 :             *guard = GcInfo {
    9635            4 :                 retain_lsns: vec![
    9636            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9637            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9638            4 :                 ],
    9639            4 :                 cutoffs: GcCutoffs {
    9640            4 :                     time: Lsn(0x30),
    9641            4 :                     space: Lsn(0x30),
    9642            4 :                 },
    9643            4 :                 leases: Default::default(),
    9644            4 :                 within_ancestor_pitr: false,
    9645            4 :             };
    9646            4 :         }
    9647            4 : 
    9648            4 :         let expected_result = [
    9649            4 :             Bytes::from_static(b"value 0@0x10"),
    9650            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9651            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9652            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9653            4 :             Bytes::from_static(b"value 4@0x10"),
    9654            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9655            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9656            4 :             Bytes::from_static(b"value 7@0x10"),
    9657            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9658            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9659            4 :         ];
    9660            4 : 
    9661            4 :         let expected_result_at_gc_horizon = [
    9662            4 :             Bytes::from_static(b"value 0@0x10"),
    9663            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9664            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9665            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9666            4 :             Bytes::from_static(b"value 4@0x10"),
    9667            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9668            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9669            4 :             Bytes::from_static(b"value 7@0x10"),
    9670            4 :             Bytes::from_static(b"value 8@0x10"),
    9671            4 :             Bytes::from_static(b"value 9@0x10"),
    9672            4 :         ];
    9673            4 : 
    9674            4 :         let expected_result_at_lsn_20 = [
    9675            4 :             Bytes::from_static(b"value 0@0x10"),
    9676            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9677            4 :             Bytes::from_static(b"value 2@0x10"),
    9678            4 :             Bytes::from_static(b"value 3@0x10"),
    9679            4 :             Bytes::from_static(b"value 4@0x10"),
    9680            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9681            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9682            4 :             Bytes::from_static(b"value 7@0x10"),
    9683            4 :             Bytes::from_static(b"value 8@0x10"),
    9684            4 :             Bytes::from_static(b"value 9@0x10"),
    9685            4 :         ];
    9686            4 : 
    9687            4 :         let expected_result_at_lsn_10 = [
    9688            4 :             Bytes::from_static(b"value 0@0x10"),
    9689            4 :             Bytes::from_static(b"value 1@0x10"),
    9690            4 :             Bytes::from_static(b"value 2@0x10"),
    9691            4 :             Bytes::from_static(b"value 3@0x10"),
    9692            4 :             Bytes::from_static(b"value 4@0x10"),
    9693            4 :             Bytes::from_static(b"value 5@0x10"),
    9694            4 :             Bytes::from_static(b"value 6@0x10"),
    9695            4 :             Bytes::from_static(b"value 7@0x10"),
    9696            4 :             Bytes::from_static(b"value 8@0x10"),
    9697            4 :             Bytes::from_static(b"value 9@0x10"),
    9698            4 :         ];
    9699            4 : 
    9700           24 :         let verify_result = || async {
    9701           24 :             let gc_horizon = {
    9702           24 :                 let gc_info = tline.gc_info.read().unwrap();
    9703           24 :                 gc_info.cutoffs.time
    9704            4 :             };
    9705          264 :             for idx in 0..10 {
    9706          240 :                 assert_eq!(
    9707          240 :                     tline
    9708          240 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9709          240 :                         .await
    9710          240 :                         .unwrap(),
    9711          240 :                     &expected_result[idx]
    9712            4 :                 );
    9713          240 :                 assert_eq!(
    9714          240 :                     tline
    9715          240 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9716          240 :                         .await
    9717          240 :                         .unwrap(),
    9718          240 :                     &expected_result_at_gc_horizon[idx]
    9719            4 :                 );
    9720          240 :                 assert_eq!(
    9721          240 :                     tline
    9722          240 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9723          240 :                         .await
    9724          240 :                         .unwrap(),
    9725          240 :                     &expected_result_at_lsn_20[idx]
    9726            4 :                 );
    9727          240 :                 assert_eq!(
    9728          240 :                     tline
    9729          240 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9730          240 :                         .await
    9731          240 :                         .unwrap(),
    9732          240 :                     &expected_result_at_lsn_10[idx]
    9733            4 :                 );
    9734            4 :             }
    9735           48 :         };
    9736            4 : 
    9737            4 :         verify_result().await;
    9738            4 : 
    9739            4 :         let cancel = CancellationToken::new();
    9740            4 :         let mut dryrun_flags = EnumSet::new();
    9741            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9742            4 : 
    9743            4 :         tline
    9744            4 :             .compact_with_gc(
    9745            4 :                 &cancel,
    9746            4 :                 CompactOptions {
    9747            4 :                     flags: dryrun_flags,
    9748            4 :                     ..Default::default()
    9749            4 :                 },
    9750            4 :                 &ctx,
    9751            4 :             )
    9752            4 :             .await
    9753            4 :             .unwrap();
    9754            4 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
    9755            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9756            4 :         verify_result().await;
    9757            4 : 
    9758            4 :         tline
    9759            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9760            4 :             .await
    9761            4 :             .unwrap();
    9762            4 :         verify_result().await;
    9763            4 : 
    9764            4 :         // compact again
    9765            4 :         tline
    9766            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9767            4 :             .await
    9768            4 :             .unwrap();
    9769            4 :         verify_result().await;
    9770            4 : 
    9771            4 :         // increase GC horizon and compact again
    9772            4 :         {
    9773            4 :             tline
    9774            4 :                 .applied_gc_cutoff_lsn
    9775            4 :                 .lock_for_write()
    9776            4 :                 .store_and_unlock(Lsn(0x38))
    9777            4 :                 .wait()
    9778            4 :                 .await;
    9779            4 :             // Update GC info
    9780            4 :             let mut guard = tline.gc_info.write().unwrap();
    9781            4 :             guard.cutoffs.time = Lsn(0x38);
    9782            4 :             guard.cutoffs.space = Lsn(0x38);
    9783            4 :         }
    9784            4 :         tline
    9785            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9786            4 :             .await
    9787            4 :             .unwrap();
    9788            4 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9789            4 : 
    9790            4 :         // not increasing the GC horizon and compact again
    9791            4 :         tline
    9792            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9793            4 :             .await
    9794            4 :             .unwrap();
    9795            4 :         verify_result().await;
    9796            4 : 
    9797            4 :         Ok(())
    9798            4 :     }
    9799              : 
    9800              :     #[cfg(feature = "testing")]
    9801              :     #[tokio::test]
    9802            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9803            4 :     {
    9804            4 :         let harness =
    9805            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9806            4 :                 .await?;
    9807            4 :         let (tenant, ctx) = harness.load().await;
    9808            4 : 
    9809          704 :         fn get_key(id: u32) -> Key {
    9810          704 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9811          704 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9812          704 :             key.field6 = id;
    9813          704 :             key
    9814          704 :         }
    9815            4 : 
    9816            4 :         let img_layer = (0..10)
    9817           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9818            4 :             .collect_vec();
    9819            4 : 
    9820            4 :         let delta1 = vec![
    9821            4 :             (
    9822            4 :                 get_key(1),
    9823            4 :                 Lsn(0x20),
    9824            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9825            4 :             ),
    9826            4 :             (
    9827            4 :                 get_key(1),
    9828            4 :                 Lsn(0x28),
    9829            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9830            4 :             ),
    9831            4 :         ];
    9832            4 :         let delta2 = vec![
    9833            4 :             (
    9834            4 :                 get_key(1),
    9835            4 :                 Lsn(0x30),
    9836            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9837            4 :             ),
    9838            4 :             (
    9839            4 :                 get_key(1),
    9840            4 :                 Lsn(0x38),
    9841            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9842            4 :             ),
    9843            4 :         ];
    9844            4 :         let delta3 = vec![
    9845            4 :             (
    9846            4 :                 get_key(8),
    9847            4 :                 Lsn(0x48),
    9848            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9849            4 :             ),
    9850            4 :             (
    9851            4 :                 get_key(9),
    9852            4 :                 Lsn(0x48),
    9853            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9854            4 :             ),
    9855            4 :         ];
    9856            4 : 
    9857            4 :         let tline = tenant
    9858            4 :             .create_test_timeline_with_layers(
    9859            4 :                 TIMELINE_ID,
    9860            4 :                 Lsn(0x10),
    9861            4 :                 DEFAULT_PG_VERSION,
    9862            4 :                 &ctx,
    9863            4 :                 Vec::new(), // in-memory layers
    9864            4 :                 vec![
    9865            4 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9866            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9867            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9868            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9869            4 :                 ], // delta layers
    9870            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9871            4 :                 Lsn(0x50),
    9872            4 :             )
    9873            4 :             .await?;
    9874            4 :         {
    9875            4 :             tline
    9876            4 :                 .applied_gc_cutoff_lsn
    9877            4 :                 .lock_for_write()
    9878            4 :                 .store_and_unlock(Lsn(0x30))
    9879            4 :                 .wait()
    9880            4 :                 .await;
    9881            4 :             // Update GC info
    9882            4 :             let mut guard = tline.gc_info.write().unwrap();
    9883            4 :             *guard = GcInfo {
    9884            4 :                 retain_lsns: vec![
    9885            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9886            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9887            4 :                 ],
    9888            4 :                 cutoffs: GcCutoffs {
    9889            4 :                     time: Lsn(0x30),
    9890            4 :                     space: Lsn(0x30),
    9891            4 :                 },
    9892            4 :                 leases: Default::default(),
    9893            4 :                 within_ancestor_pitr: false,
    9894            4 :             };
    9895            4 :         }
    9896            4 : 
    9897            4 :         let expected_result = [
    9898            4 :             Bytes::from_static(b"value 0@0x10"),
    9899            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9900            4 :             Bytes::from_static(b"value 2@0x10"),
    9901            4 :             Bytes::from_static(b"value 3@0x10"),
    9902            4 :             Bytes::from_static(b"value 4@0x10"),
    9903            4 :             Bytes::from_static(b"value 5@0x10"),
    9904            4 :             Bytes::from_static(b"value 6@0x10"),
    9905            4 :             Bytes::from_static(b"value 7@0x10"),
    9906            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9907            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9908            4 :         ];
    9909            4 : 
    9910            4 :         let expected_result_at_gc_horizon = [
    9911            4 :             Bytes::from_static(b"value 0@0x10"),
    9912            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9913            4 :             Bytes::from_static(b"value 2@0x10"),
    9914            4 :             Bytes::from_static(b"value 3@0x10"),
    9915            4 :             Bytes::from_static(b"value 4@0x10"),
    9916            4 :             Bytes::from_static(b"value 5@0x10"),
    9917            4 :             Bytes::from_static(b"value 6@0x10"),
    9918            4 :             Bytes::from_static(b"value 7@0x10"),
    9919            4 :             Bytes::from_static(b"value 8@0x10"),
    9920            4 :             Bytes::from_static(b"value 9@0x10"),
    9921            4 :         ];
    9922            4 : 
    9923            4 :         let expected_result_at_lsn_20 = [
    9924            4 :             Bytes::from_static(b"value 0@0x10"),
    9925            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9926            4 :             Bytes::from_static(b"value 2@0x10"),
    9927            4 :             Bytes::from_static(b"value 3@0x10"),
    9928            4 :             Bytes::from_static(b"value 4@0x10"),
    9929            4 :             Bytes::from_static(b"value 5@0x10"),
    9930            4 :             Bytes::from_static(b"value 6@0x10"),
    9931            4 :             Bytes::from_static(b"value 7@0x10"),
    9932            4 :             Bytes::from_static(b"value 8@0x10"),
    9933            4 :             Bytes::from_static(b"value 9@0x10"),
    9934            4 :         ];
    9935            4 : 
    9936            4 :         let expected_result_at_lsn_10 = [
    9937            4 :             Bytes::from_static(b"value 0@0x10"),
    9938            4 :             Bytes::from_static(b"value 1@0x10"),
    9939            4 :             Bytes::from_static(b"value 2@0x10"),
    9940            4 :             Bytes::from_static(b"value 3@0x10"),
    9941            4 :             Bytes::from_static(b"value 4@0x10"),
    9942            4 :             Bytes::from_static(b"value 5@0x10"),
    9943            4 :             Bytes::from_static(b"value 6@0x10"),
    9944            4 :             Bytes::from_static(b"value 7@0x10"),
    9945            4 :             Bytes::from_static(b"value 8@0x10"),
    9946            4 :             Bytes::from_static(b"value 9@0x10"),
    9947            4 :         ];
    9948            4 : 
    9949           16 :         let verify_result = || async {
    9950           16 :             let gc_horizon = {
    9951           16 :                 let gc_info = tline.gc_info.read().unwrap();
    9952           16 :                 gc_info.cutoffs.time
    9953            4 :             };
    9954          176 :             for idx in 0..10 {
    9955          160 :                 assert_eq!(
    9956          160 :                     tline
    9957          160 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9958          160 :                         .await
    9959          160 :                         .unwrap(),
    9960          160 :                     &expected_result[idx]
    9961            4 :                 );
    9962          160 :                 assert_eq!(
    9963          160 :                     tline
    9964          160 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9965          160 :                         .await
    9966          160 :                         .unwrap(),
    9967          160 :                     &expected_result_at_gc_horizon[idx]
    9968            4 :                 );
    9969          160 :                 assert_eq!(
    9970          160 :                     tline
    9971          160 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9972          160 :                         .await
    9973          160 :                         .unwrap(),
    9974          160 :                     &expected_result_at_lsn_20[idx]
    9975            4 :                 );
    9976          160 :                 assert_eq!(
    9977          160 :                     tline
    9978          160 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9979          160 :                         .await
    9980          160 :                         .unwrap(),
    9981          160 :                     &expected_result_at_lsn_10[idx]
    9982            4 :                 );
    9983            4 :             }
    9984           32 :         };
    9985            4 : 
    9986            4 :         verify_result().await;
    9987            4 : 
    9988            4 :         let cancel = CancellationToken::new();
    9989            4 :         let mut dryrun_flags = EnumSet::new();
    9990            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9991            4 : 
    9992            4 :         tline
    9993            4 :             .compact_with_gc(
    9994            4 :                 &cancel,
    9995            4 :                 CompactOptions {
    9996            4 :                     flags: dryrun_flags,
    9997            4 :                     ..Default::default()
    9998            4 :                 },
    9999            4 :                 &ctx,
   10000            4 :             )
   10001            4 :             .await
   10002            4 :             .unwrap();
   10003            4 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
   10004            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10005            4 :         verify_result().await;
   10006            4 : 
   10007            4 :         tline
   10008            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10009            4 :             .await
   10010            4 :             .unwrap();
   10011            4 :         verify_result().await;
   10012            4 : 
   10013            4 :         // compact again
   10014            4 :         tline
   10015            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10016            4 :             .await
   10017            4 :             .unwrap();
   10018            4 :         verify_result().await;
   10019            4 : 
   10020            4 :         Ok(())
   10021            4 :     }
   10022              : 
   10023              :     #[cfg(feature = "testing")]
   10024              :     #[tokio::test]
   10025            4 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10026            4 :         use models::CompactLsnRange;
   10027            4 : 
   10028            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10029            4 :         let (tenant, ctx) = harness.load().await;
   10030            4 : 
   10031          332 :         fn get_key(id: u32) -> Key {
   10032          332 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10033          332 :             key.field6 = id;
   10034          332 :             key
   10035          332 :         }
   10036            4 : 
   10037            4 :         let img_layer = (0..10)
   10038           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10039            4 :             .collect_vec();
   10040            4 : 
   10041            4 :         let delta1 = vec![
   10042            4 :             (
   10043            4 :                 get_key(1),
   10044            4 :                 Lsn(0x20),
   10045            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10046            4 :             ),
   10047            4 :             (
   10048            4 :                 get_key(2),
   10049            4 :                 Lsn(0x30),
   10050            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10051            4 :             ),
   10052            4 :             (
   10053            4 :                 get_key(3),
   10054            4 :                 Lsn(0x28),
   10055            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10056            4 :             ),
   10057            4 :             (
   10058            4 :                 get_key(3),
   10059            4 :                 Lsn(0x30),
   10060            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10061            4 :             ),
   10062            4 :             (
   10063            4 :                 get_key(3),
   10064            4 :                 Lsn(0x40),
   10065            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10066            4 :             ),
   10067            4 :         ];
   10068            4 :         let delta2 = vec![
   10069            4 :             (
   10070            4 :                 get_key(5),
   10071            4 :                 Lsn(0x20),
   10072            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10073            4 :             ),
   10074            4 :             (
   10075            4 :                 get_key(6),
   10076            4 :                 Lsn(0x20),
   10077            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10078            4 :             ),
   10079            4 :         ];
   10080            4 :         let delta3 = vec![
   10081            4 :             (
   10082            4 :                 get_key(8),
   10083            4 :                 Lsn(0x48),
   10084            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10085            4 :             ),
   10086            4 :             (
   10087            4 :                 get_key(9),
   10088            4 :                 Lsn(0x48),
   10089            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10090            4 :             ),
   10091            4 :         ];
   10092            4 : 
   10093            4 :         let parent_tline = tenant
   10094            4 :             .create_test_timeline_with_layers(
   10095            4 :                 TIMELINE_ID,
   10096            4 :                 Lsn(0x10),
   10097            4 :                 DEFAULT_PG_VERSION,
   10098            4 :                 &ctx,
   10099            4 :                 vec![],                       // in-memory layers
   10100            4 :                 vec![],                       // delta layers
   10101            4 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10102            4 :                 Lsn(0x18),
   10103            4 :             )
   10104            4 :             .await?;
   10105            4 : 
   10106            4 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10107            4 : 
   10108            4 :         let branch_tline = tenant
   10109            4 :             .branch_timeline_test_with_layers(
   10110            4 :                 &parent_tline,
   10111            4 :                 NEW_TIMELINE_ID,
   10112            4 :                 Some(Lsn(0x18)),
   10113            4 :                 &ctx,
   10114            4 :                 vec![
   10115            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10116            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10117            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10118            4 :                 ], // delta layers
   10119            4 :                 vec![], // image layers
   10120            4 :                 Lsn(0x50),
   10121            4 :             )
   10122            4 :             .await?;
   10123            4 : 
   10124            4 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10125            4 : 
   10126            4 :         {
   10127            4 :             parent_tline
   10128            4 :                 .applied_gc_cutoff_lsn
   10129            4 :                 .lock_for_write()
   10130            4 :                 .store_and_unlock(Lsn(0x10))
   10131            4 :                 .wait()
   10132            4 :                 .await;
   10133            4 :             // Update GC info
   10134            4 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10135            4 :             *guard = GcInfo {
   10136            4 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10137            4 :                 cutoffs: GcCutoffs {
   10138            4 :                     time: Lsn(0x10),
   10139            4 :                     space: Lsn(0x10),
   10140            4 :                 },
   10141            4 :                 leases: Default::default(),
   10142            4 :                 within_ancestor_pitr: false,
   10143            4 :             };
   10144            4 :         }
   10145            4 : 
   10146            4 :         {
   10147            4 :             branch_tline
   10148            4 :                 .applied_gc_cutoff_lsn
   10149            4 :                 .lock_for_write()
   10150            4 :                 .store_and_unlock(Lsn(0x50))
   10151            4 :                 .wait()
   10152            4 :                 .await;
   10153            4 :             // Update GC info
   10154            4 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10155            4 :             *guard = GcInfo {
   10156            4 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10157            4 :                 cutoffs: GcCutoffs {
   10158            4 :                     time: Lsn(0x50),
   10159            4 :                     space: Lsn(0x50),
   10160            4 :                 },
   10161            4 :                 leases: Default::default(),
   10162            4 :                 within_ancestor_pitr: false,
   10163            4 :             };
   10164            4 :         }
   10165            4 : 
   10166            4 :         let expected_result_at_gc_horizon = [
   10167            4 :             Bytes::from_static(b"value 0@0x10"),
   10168            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10169            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10170            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10171            4 :             Bytes::from_static(b"value 4@0x10"),
   10172            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10173            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10174            4 :             Bytes::from_static(b"value 7@0x10"),
   10175            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10176            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10177            4 :         ];
   10178            4 : 
   10179            4 :         let expected_result_at_lsn_40 = [
   10180            4 :             Bytes::from_static(b"value 0@0x10"),
   10181            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10182            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10183            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10184            4 :             Bytes::from_static(b"value 4@0x10"),
   10185            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10186            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10187            4 :             Bytes::from_static(b"value 7@0x10"),
   10188            4 :             Bytes::from_static(b"value 8@0x10"),
   10189            4 :             Bytes::from_static(b"value 9@0x10"),
   10190            4 :         ];
   10191            4 : 
   10192           12 :         let verify_result = || async {
   10193          132 :             for idx in 0..10 {
   10194          120 :                 assert_eq!(
   10195          120 :                     branch_tline
   10196          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10197          120 :                         .await
   10198          120 :                         .unwrap(),
   10199          120 :                     &expected_result_at_gc_horizon[idx]
   10200            4 :                 );
   10201          120 :                 assert_eq!(
   10202          120 :                     branch_tline
   10203          120 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10204          120 :                         .await
   10205          120 :                         .unwrap(),
   10206          120 :                     &expected_result_at_lsn_40[idx]
   10207            4 :                 );
   10208            4 :             }
   10209           24 :         };
   10210            4 : 
   10211            4 :         verify_result().await;
   10212            4 : 
   10213            4 :         let cancel = CancellationToken::new();
   10214            4 :         branch_tline
   10215            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10216            4 :             .await
   10217            4 :             .unwrap();
   10218            4 : 
   10219            4 :         verify_result().await;
   10220            4 : 
   10221            4 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10222            4 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10223            4 :         branch_tline
   10224            4 :             .compact_with_gc(
   10225            4 :                 &cancel,
   10226            4 :                 CompactOptions {
   10227            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10228            4 :                     ..Default::default()
   10229            4 :                 },
   10230            4 :                 &ctx,
   10231            4 :             )
   10232            4 :             .await
   10233            4 :             .unwrap();
   10234            4 : 
   10235            4 :         verify_result().await;
   10236            4 : 
   10237            4 :         Ok(())
   10238            4 :     }
   10239              : 
   10240              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10241              :     // Create an image arrangement where we have to read at different LSN ranges
   10242              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10243              :     // a delta layer. Like so:
   10244              :     //
   10245              :     //     A      B
   10246              :     // +----------------+ -> delta_layer
   10247              :     // |                |                           ^ lsn
   10248              :     // |       =========|-> nested_image_layer      |
   10249              :     // |       C        |                           |
   10250              :     // +----------------+                           |
   10251              :     // ======== -> baseline_image_layer             +-------> key
   10252              :     //
   10253              :     //
   10254              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10255              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10256              :     #[cfg(feature = "testing")]
   10257              :     #[tokio::test]
   10258            4 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10259            4 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10260            4 :         let (tenant, ctx) = harness.load().await;
   10261            4 : 
   10262            4 :         let will_init_keys = [2, 6];
   10263           88 :         fn get_key(id: u32) -> Key {
   10264           88 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10265           88 :             key.field6 = id;
   10266           88 :             key
   10267           88 :         }
   10268            4 : 
   10269            4 :         let mut expected_key_values = HashMap::new();
   10270            4 : 
   10271            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10272            4 :         let mut baseline_img_layer = Vec::new();
   10273           24 :         for i in 0..5 {
   10274           20 :             let key = get_key(i);
   10275           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10276           20 : 
   10277           20 :             let removed = expected_key_values.insert(key, value.clone());
   10278           20 :             assert!(removed.is_none());
   10279            4 : 
   10280           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10281            4 :         }
   10282            4 : 
   10283            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10284            4 :         let mut nested_img_layer = Vec::new();
   10285           24 :         for i in 5..10 {
   10286           20 :             let key = get_key(i);
   10287           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10288           20 : 
   10289           20 :             let removed = expected_key_values.insert(key, value.clone());
   10290           20 :             assert!(removed.is_none());
   10291            4 : 
   10292           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10293            4 :         }
   10294            4 : 
   10295            4 :         let mut delta_layer_spec = Vec::default();
   10296            4 :         let delta_layer_start_lsn = Lsn(0x20);
   10297            4 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10298            4 : 
   10299           44 :         for i in 0..10 {
   10300           40 :             let key = get_key(i);
   10301           40 :             let key_in_nested = nested_img_layer
   10302           40 :                 .iter()
   10303          160 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10304           40 :             let lsn = {
   10305           40 :                 if key_in_nested {
   10306           20 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10307            4 :                 } else {
   10308           20 :                     delta_layer_start_lsn
   10309            4 :                 }
   10310            4 :             };
   10311            4 : 
   10312           40 :             let will_init = will_init_keys.contains(&i);
   10313           40 :             if will_init {
   10314            8 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10315            8 : 
   10316            8 :                 expected_key_values.insert(key, "".to_string());
   10317           32 :             } else {
   10318           32 :                 let delta = format!("@{lsn}");
   10319           32 :                 delta_layer_spec.push((
   10320           32 :                     key,
   10321           32 :                     lsn,
   10322           32 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10323           32 :                 ));
   10324           32 : 
   10325           32 :                 expected_key_values
   10326           32 :                     .get_mut(&key)
   10327           32 :                     .expect("An image exists for each key")
   10328           32 :                     .push_str(delta.as_str());
   10329           32 :             }
   10330           40 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10331            4 :         }
   10332            4 : 
   10333            4 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10334            4 : 
   10335            4 :         assert!(
   10336            4 :             nested_image_layer_lsn > delta_layer_start_lsn
   10337            4 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10338            4 :         );
   10339            4 : 
   10340            4 :         let tline = tenant
   10341            4 :             .create_test_timeline_with_layers(
   10342            4 :                 TIMELINE_ID,
   10343            4 :                 baseline_image_layer_lsn,
   10344            4 :                 DEFAULT_PG_VERSION,
   10345            4 :                 &ctx,
   10346            4 :                 vec![], // in-memory layers
   10347            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10348            4 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10349            4 :                     delta_layer_spec,
   10350            4 :                 )], // delta layers
   10351            4 :                 vec![
   10352            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10353            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10354            4 :                 ], // image layers
   10355            4 :                 delta_layer_end_lsn,
   10356            4 :             )
   10357            4 :             .await?;
   10358            4 : 
   10359            4 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10360            4 :         let results = tline
   10361            4 :             .get_vectored(
   10362            4 :                 keyspace,
   10363            4 :                 delta_layer_end_lsn,
   10364            4 :                 IoConcurrency::sequential(),
   10365            4 :                 &ctx,
   10366            4 :             )
   10367            4 :             .await
   10368            4 :             .expect("No vectored errors");
   10369           44 :         for (key, res) in results {
   10370           40 :             let value = res.expect("No key errors");
   10371           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10372           40 :             assert_eq!(value, Bytes::from(expected_value));
   10373            4 :         }
   10374            4 : 
   10375            4 :         Ok(())
   10376            4 :     }
   10377              : 
   10378              :     #[cfg(feature = "testing")]
   10379              :     #[tokio::test]
   10380            4 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   10381            4 :         let harness =
   10382            4 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   10383            4 :         let (tenant, ctx) = harness.load().await;
   10384            4 : 
   10385            4 :         let will_init_keys = [2, 6];
   10386          128 :         fn get_key(id: u32) -> Key {
   10387          128 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10388          128 :             key.field6 = id;
   10389          128 :             key
   10390          128 :         }
   10391            4 : 
   10392            4 :         let mut expected_key_values = HashMap::new();
   10393            4 : 
   10394            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10395            4 :         let mut baseline_img_layer = Vec::new();
   10396           24 :         for i in 0..5 {
   10397           20 :             let key = get_key(i);
   10398           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10399           20 : 
   10400           20 :             let removed = expected_key_values.insert(key, value.clone());
   10401           20 :             assert!(removed.is_none());
   10402            4 : 
   10403           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10404            4 :         }
   10405            4 : 
   10406            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10407            4 :         let mut nested_img_layer = Vec::new();
   10408           24 :         for i in 5..10 {
   10409           20 :             let key = get_key(i);
   10410           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10411           20 : 
   10412           20 :             let removed = expected_key_values.insert(key, value.clone());
   10413           20 :             assert!(removed.is_none());
   10414            4 : 
   10415           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10416            4 :         }
   10417            4 : 
   10418            4 :         let frozen_layer = {
   10419            4 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   10420            4 :             let mut data = Vec::new();
   10421           44 :             for i in 0..10 {
   10422           40 :                 let key = get_key(i);
   10423           40 :                 let key_in_nested = nested_img_layer
   10424           40 :                     .iter()
   10425          160 :                     .any(|(key_with_img, _)| *key_with_img == key);
   10426           40 :                 let lsn = {
   10427           40 :                     if key_in_nested {
   10428           20 :                         Lsn(nested_image_layer_lsn.0 + 5)
   10429            4 :                     } else {
   10430           20 :                         lsn_range.start
   10431            4 :                     }
   10432            4 :                 };
   10433            4 : 
   10434           40 :                 let will_init = will_init_keys.contains(&i);
   10435           40 :                 if will_init {
   10436            8 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10437            8 : 
   10438            8 :                     expected_key_values.insert(key, "".to_string());
   10439           32 :                 } else {
   10440           32 :                     let delta = format!("@{lsn}");
   10441           32 :                     data.push((
   10442           32 :                         key,
   10443           32 :                         lsn,
   10444           32 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10445           32 :                     ));
   10446           32 : 
   10447           32 :                     expected_key_values
   10448           32 :                         .get_mut(&key)
   10449           32 :                         .expect("An image exists for each key")
   10450           32 :                         .push_str(delta.as_str());
   10451           32 :                 }
   10452            4 :             }
   10453            4 : 
   10454            4 :             InMemoryLayerTestDesc {
   10455            4 :                 lsn_range,
   10456            4 :                 is_open: false,
   10457            4 :                 data,
   10458            4 :             }
   10459            4 :         };
   10460            4 : 
   10461            4 :         let (open_layer, last_record_lsn) = {
   10462            4 :             let start_lsn = Lsn(0x70);
   10463            4 :             let mut data = Vec::new();
   10464            4 :             let mut end_lsn = Lsn(0);
   10465           44 :             for i in 0..10 {
   10466           40 :                 let key = get_key(i);
   10467           40 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   10468           40 :                 let delta = format!("@{lsn}");
   10469           40 :                 data.push((
   10470           40 :                     key,
   10471           40 :                     lsn,
   10472           40 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10473           40 :                 ));
   10474           40 : 
   10475           40 :                 expected_key_values
   10476           40 :                     .get_mut(&key)
   10477           40 :                     .expect("An image exists for each key")
   10478           40 :                     .push_str(delta.as_str());
   10479           40 : 
   10480           40 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   10481           40 :             }
   10482            4 : 
   10483            4 :             (
   10484            4 :                 InMemoryLayerTestDesc {
   10485            4 :                     lsn_range: start_lsn..Lsn::MAX,
   10486            4 :                     is_open: true,
   10487            4 :                     data,
   10488            4 :                 },
   10489            4 :                 end_lsn,
   10490            4 :             )
   10491            4 :         };
   10492            4 : 
   10493            4 :         assert!(
   10494            4 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   10495            4 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   10496            4 :         );
   10497            4 : 
   10498            4 :         let tline = tenant
   10499            4 :             .create_test_timeline_with_layers(
   10500            4 :                 TIMELINE_ID,
   10501            4 :                 baseline_image_layer_lsn,
   10502            4 :                 DEFAULT_PG_VERSION,
   10503            4 :                 &ctx,
   10504            4 :                 vec![open_layer, frozen_layer], // in-memory layers
   10505            4 :                 Vec::new(),                     // delta layers
   10506            4 :                 vec![
   10507            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10508            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10509            4 :                 ], // image layers
   10510            4 :                 last_record_lsn,
   10511            4 :             )
   10512            4 :             .await?;
   10513            4 : 
   10514            4 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10515            4 :         let results = tline
   10516            4 :             .get_vectored(keyspace, last_record_lsn, IoConcurrency::sequential(), &ctx)
   10517            4 :             .await
   10518            4 :             .expect("No vectored errors");
   10519           44 :         for (key, res) in results {
   10520           40 :             let value = res.expect("No key errors");
   10521           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10522           40 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   10523            4 : 
   10524           40 :             tracing::info!("key={key} value={expected_value}");
   10525            4 :         }
   10526            4 : 
   10527            4 :         Ok(())
   10528            4 :     }
   10529              : 
   10530          428 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   10531          428 :         (
   10532          428 :             k1.is_delta,
   10533          428 :             k1.key_range.start,
   10534          428 :             k1.key_range.end,
   10535          428 :             k1.lsn_range.start,
   10536          428 :             k1.lsn_range.end,
   10537          428 :         )
   10538          428 :             .cmp(&(
   10539          428 :                 k2.is_delta,
   10540          428 :                 k2.key_range.start,
   10541          428 :                 k2.key_range.end,
   10542          428 :                 k2.lsn_range.start,
   10543          428 :                 k2.lsn_range.end,
   10544          428 :             ))
   10545          428 :     }
   10546              : 
   10547           48 :     async fn inspect_and_sort(
   10548           48 :         tline: &Arc<Timeline>,
   10549           48 :         filter: Option<std::ops::Range<Key>>,
   10550           48 :     ) -> Vec<PersistentLayerKey> {
   10551           48 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   10552           48 :         if let Some(filter) = filter {
   10553          216 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   10554           44 :         }
   10555           48 :         all_layers.sort_by(sort_layer_key);
   10556           48 :         all_layers
   10557           48 :     }
   10558              : 
   10559              :     #[cfg(feature = "testing")]
   10560           44 :     fn check_layer_map_key_eq(
   10561           44 :         mut left: Vec<PersistentLayerKey>,
   10562           44 :         mut right: Vec<PersistentLayerKey>,
   10563           44 :     ) {
   10564           44 :         left.sort_by(sort_layer_key);
   10565           44 :         right.sort_by(sort_layer_key);
   10566           44 :         if left != right {
   10567            0 :             eprintln!("---LEFT---");
   10568            0 :             for left in left.iter() {
   10569            0 :                 eprintln!("{}", left);
   10570            0 :             }
   10571            0 :             eprintln!("---RIGHT---");
   10572            0 :             for right in right.iter() {
   10573            0 :                 eprintln!("{}", right);
   10574            0 :             }
   10575            0 :             assert_eq!(left, right);
   10576           44 :         }
   10577           44 :     }
   10578              : 
   10579              :     #[cfg(feature = "testing")]
   10580              :     #[tokio::test]
   10581            4 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   10582            4 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   10583            4 :         let (tenant, ctx) = harness.load().await;
   10584            4 : 
   10585          364 :         fn get_key(id: u32) -> Key {
   10586          364 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10587          364 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10588          364 :             key.field6 = id;
   10589          364 :             key
   10590          364 :         }
   10591            4 : 
   10592            4 :         // img layer at 0x10
   10593            4 :         let img_layer = (0..10)
   10594           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10595            4 :             .collect_vec();
   10596            4 : 
   10597            4 :         let delta1 = vec![
   10598            4 :             (
   10599            4 :                 get_key(1),
   10600            4 :                 Lsn(0x20),
   10601            4 :                 Value::Image(Bytes::from("value 1@0x20")),
   10602            4 :             ),
   10603            4 :             (
   10604            4 :                 get_key(2),
   10605            4 :                 Lsn(0x30),
   10606            4 :                 Value::Image(Bytes::from("value 2@0x30")),
   10607            4 :             ),
   10608            4 :             (
   10609            4 :                 get_key(3),
   10610            4 :                 Lsn(0x40),
   10611            4 :                 Value::Image(Bytes::from("value 3@0x40")),
   10612            4 :             ),
   10613            4 :         ];
   10614            4 :         let delta2 = vec![
   10615            4 :             (
   10616            4 :                 get_key(5),
   10617            4 :                 Lsn(0x20),
   10618            4 :                 Value::Image(Bytes::from("value 5@0x20")),
   10619            4 :             ),
   10620            4 :             (
   10621            4 :                 get_key(6),
   10622            4 :                 Lsn(0x20),
   10623            4 :                 Value::Image(Bytes::from("value 6@0x20")),
   10624            4 :             ),
   10625            4 :         ];
   10626            4 :         let delta3 = vec![
   10627            4 :             (
   10628            4 :                 get_key(8),
   10629            4 :                 Lsn(0x48),
   10630            4 :                 Value::Image(Bytes::from("value 8@0x48")),
   10631            4 :             ),
   10632            4 :             (
   10633            4 :                 get_key(9),
   10634            4 :                 Lsn(0x48),
   10635            4 :                 Value::Image(Bytes::from("value 9@0x48")),
   10636            4 :             ),
   10637            4 :         ];
   10638            4 : 
   10639            4 :         let tline = tenant
   10640            4 :             .create_test_timeline_with_layers(
   10641            4 :                 TIMELINE_ID,
   10642            4 :                 Lsn(0x10),
   10643            4 :                 DEFAULT_PG_VERSION,
   10644            4 :                 &ctx,
   10645            4 :                 vec![], // in-memory layers
   10646            4 :                 vec![
   10647            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10648            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10649            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10650            4 :                 ], // delta layers
   10651            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10652            4 :                 Lsn(0x50),
   10653            4 :             )
   10654            4 :             .await?;
   10655            4 : 
   10656            4 :         {
   10657            4 :             tline
   10658            4 :                 .applied_gc_cutoff_lsn
   10659            4 :                 .lock_for_write()
   10660            4 :                 .store_and_unlock(Lsn(0x30))
   10661            4 :                 .wait()
   10662            4 :                 .await;
   10663            4 :             // Update GC info
   10664            4 :             let mut guard = tline.gc_info.write().unwrap();
   10665            4 :             *guard = GcInfo {
   10666            4 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10667            4 :                 cutoffs: GcCutoffs {
   10668            4 :                     time: Lsn(0x30),
   10669            4 :                     space: Lsn(0x30),
   10670            4 :                 },
   10671            4 :                 leases: Default::default(),
   10672            4 :                 within_ancestor_pitr: false,
   10673            4 :             };
   10674            4 :         }
   10675            4 : 
   10676            4 :         let cancel = CancellationToken::new();
   10677            4 : 
   10678            4 :         // Do a partial compaction on key range 0..2
   10679            4 :         tline
   10680            4 :             .compact_with_gc(
   10681            4 :                 &cancel,
   10682            4 :                 CompactOptions {
   10683            4 :                     flags: EnumSet::new(),
   10684            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10685            4 :                     ..Default::default()
   10686            4 :                 },
   10687            4 :                 &ctx,
   10688            4 :             )
   10689            4 :             .await
   10690            4 :             .unwrap();
   10691            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10692            4 :         check_layer_map_key_eq(
   10693            4 :             all_layers,
   10694            4 :             vec![
   10695            4 :                 // newly-generated image layer for the partial compaction range 0-2
   10696            4 :                 PersistentLayerKey {
   10697            4 :                     key_range: get_key(0)..get_key(2),
   10698            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10699            4 :                     is_delta: false,
   10700            4 :                 },
   10701            4 :                 PersistentLayerKey {
   10702            4 :                     key_range: get_key(0)..get_key(10),
   10703            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10704            4 :                     is_delta: false,
   10705            4 :                 },
   10706            4 :                 // delta1 is split and the second part is rewritten
   10707            4 :                 PersistentLayerKey {
   10708            4 :                     key_range: get_key(2)..get_key(4),
   10709            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10710            4 :                     is_delta: true,
   10711            4 :                 },
   10712            4 :                 PersistentLayerKey {
   10713            4 :                     key_range: get_key(5)..get_key(7),
   10714            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10715            4 :                     is_delta: true,
   10716            4 :                 },
   10717            4 :                 PersistentLayerKey {
   10718            4 :                     key_range: get_key(8)..get_key(10),
   10719            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10720            4 :                     is_delta: true,
   10721            4 :                 },
   10722            4 :             ],
   10723            4 :         );
   10724            4 : 
   10725            4 :         // Do a partial compaction on key range 2..4
   10726            4 :         tline
   10727            4 :             .compact_with_gc(
   10728            4 :                 &cancel,
   10729            4 :                 CompactOptions {
   10730            4 :                     flags: EnumSet::new(),
   10731            4 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   10732            4 :                     ..Default::default()
   10733            4 :                 },
   10734            4 :                 &ctx,
   10735            4 :             )
   10736            4 :             .await
   10737            4 :             .unwrap();
   10738            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10739            4 :         check_layer_map_key_eq(
   10740            4 :             all_layers,
   10741            4 :             vec![
   10742            4 :                 PersistentLayerKey {
   10743            4 :                     key_range: get_key(0)..get_key(2),
   10744            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10745            4 :                     is_delta: false,
   10746            4 :                 },
   10747            4 :                 PersistentLayerKey {
   10748            4 :                     key_range: get_key(0)..get_key(10),
   10749            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10750            4 :                     is_delta: false,
   10751            4 :                 },
   10752            4 :                 // image layer generated for the compaction range 2-4
   10753            4 :                 PersistentLayerKey {
   10754            4 :                     key_range: get_key(2)..get_key(4),
   10755            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10756            4 :                     is_delta: false,
   10757            4 :                 },
   10758            4 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10759            4 :                 PersistentLayerKey {
   10760            4 :                     key_range: get_key(2)..get_key(4),
   10761            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10762            4 :                     is_delta: true,
   10763            4 :                 },
   10764            4 :                 PersistentLayerKey {
   10765            4 :                     key_range: get_key(5)..get_key(7),
   10766            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10767            4 :                     is_delta: true,
   10768            4 :                 },
   10769            4 :                 PersistentLayerKey {
   10770            4 :                     key_range: get_key(8)..get_key(10),
   10771            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10772            4 :                     is_delta: true,
   10773            4 :                 },
   10774            4 :             ],
   10775            4 :         );
   10776            4 : 
   10777            4 :         // Do a partial compaction on key range 4..9
   10778            4 :         tline
   10779            4 :             .compact_with_gc(
   10780            4 :                 &cancel,
   10781            4 :                 CompactOptions {
   10782            4 :                     flags: EnumSet::new(),
   10783            4 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   10784            4 :                     ..Default::default()
   10785            4 :                 },
   10786            4 :                 &ctx,
   10787            4 :             )
   10788            4 :             .await
   10789            4 :             .unwrap();
   10790            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10791            4 :         check_layer_map_key_eq(
   10792            4 :             all_layers,
   10793            4 :             vec![
   10794            4 :                 PersistentLayerKey {
   10795            4 :                     key_range: get_key(0)..get_key(2),
   10796            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10797            4 :                     is_delta: false,
   10798            4 :                 },
   10799            4 :                 PersistentLayerKey {
   10800            4 :                     key_range: get_key(0)..get_key(10),
   10801            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10802            4 :                     is_delta: false,
   10803            4 :                 },
   10804            4 :                 PersistentLayerKey {
   10805            4 :                     key_range: get_key(2)..get_key(4),
   10806            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10807            4 :                     is_delta: false,
   10808            4 :                 },
   10809            4 :                 PersistentLayerKey {
   10810            4 :                     key_range: get_key(2)..get_key(4),
   10811            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10812            4 :                     is_delta: true,
   10813            4 :                 },
   10814            4 :                 // image layer generated for this compaction range
   10815            4 :                 PersistentLayerKey {
   10816            4 :                     key_range: get_key(4)..get_key(9),
   10817            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10818            4 :                     is_delta: false,
   10819            4 :                 },
   10820            4 :                 PersistentLayerKey {
   10821            4 :                     key_range: get_key(8)..get_key(10),
   10822            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10823            4 :                     is_delta: true,
   10824            4 :                 },
   10825            4 :             ],
   10826            4 :         );
   10827            4 : 
   10828            4 :         // Do a partial compaction on key range 9..10
   10829            4 :         tline
   10830            4 :             .compact_with_gc(
   10831            4 :                 &cancel,
   10832            4 :                 CompactOptions {
   10833            4 :                     flags: EnumSet::new(),
   10834            4 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   10835            4 :                     ..Default::default()
   10836            4 :                 },
   10837            4 :                 &ctx,
   10838            4 :             )
   10839            4 :             .await
   10840            4 :             .unwrap();
   10841            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10842            4 :         check_layer_map_key_eq(
   10843            4 :             all_layers,
   10844            4 :             vec![
   10845            4 :                 PersistentLayerKey {
   10846            4 :                     key_range: get_key(0)..get_key(2),
   10847            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10848            4 :                     is_delta: false,
   10849            4 :                 },
   10850            4 :                 PersistentLayerKey {
   10851            4 :                     key_range: get_key(0)..get_key(10),
   10852            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10853            4 :                     is_delta: false,
   10854            4 :                 },
   10855            4 :                 PersistentLayerKey {
   10856            4 :                     key_range: get_key(2)..get_key(4),
   10857            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10858            4 :                     is_delta: false,
   10859            4 :                 },
   10860            4 :                 PersistentLayerKey {
   10861            4 :                     key_range: get_key(2)..get_key(4),
   10862            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10863            4 :                     is_delta: true,
   10864            4 :                 },
   10865            4 :                 PersistentLayerKey {
   10866            4 :                     key_range: get_key(4)..get_key(9),
   10867            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10868            4 :                     is_delta: false,
   10869            4 :                 },
   10870            4 :                 // image layer generated for the compaction range
   10871            4 :                 PersistentLayerKey {
   10872            4 :                     key_range: get_key(9)..get_key(10),
   10873            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10874            4 :                     is_delta: false,
   10875            4 :                 },
   10876            4 :                 PersistentLayerKey {
   10877            4 :                     key_range: get_key(8)..get_key(10),
   10878            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10879            4 :                     is_delta: true,
   10880            4 :                 },
   10881            4 :             ],
   10882            4 :         );
   10883            4 : 
   10884            4 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10885            4 :         tline
   10886            4 :             .compact_with_gc(
   10887            4 :                 &cancel,
   10888            4 :                 CompactOptions {
   10889            4 :                     flags: EnumSet::new(),
   10890            4 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   10891            4 :                     ..Default::default()
   10892            4 :                 },
   10893            4 :                 &ctx,
   10894            4 :             )
   10895            4 :             .await
   10896            4 :             .unwrap();
   10897            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10898            4 :         check_layer_map_key_eq(
   10899            4 :             all_layers,
   10900            4 :             vec![
   10901            4 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10902            4 :                 PersistentLayerKey {
   10903            4 :                     key_range: get_key(0)..get_key(10),
   10904            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10905            4 :                     is_delta: false,
   10906            4 :                 },
   10907            4 :                 PersistentLayerKey {
   10908            4 :                     key_range: get_key(2)..get_key(4),
   10909            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10910            4 :                     is_delta: true,
   10911            4 :                 },
   10912            4 :                 PersistentLayerKey {
   10913            4 :                     key_range: get_key(8)..get_key(10),
   10914            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10915            4 :                     is_delta: true,
   10916            4 :                 },
   10917            4 :             ],
   10918            4 :         );
   10919            4 :         Ok(())
   10920            4 :     }
   10921              : 
   10922              :     #[cfg(feature = "testing")]
   10923              :     #[tokio::test]
   10924            4 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10925            4 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10926            4 :             .await
   10927            4 :             .unwrap();
   10928            4 :         let (tenant, ctx) = harness.load().await;
   10929            4 :         let tline_parent = tenant
   10930            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10931            4 :             .await
   10932            4 :             .unwrap();
   10933            4 :         let tline_child = tenant
   10934            4 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10935            4 :             .await
   10936            4 :             .unwrap();
   10937            4 :         {
   10938            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10939            4 :             assert_eq!(
   10940            4 :                 gc_info_parent.retain_lsns,
   10941            4 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10942            4 :             );
   10943            4 :         }
   10944            4 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10945            4 :         tline_child
   10946            4 :             .remote_client
   10947            4 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10948            4 :             .unwrap();
   10949            4 :         tline_child.remote_client.wait_completion().await.unwrap();
   10950            4 :         offload_timeline(&tenant, &tline_child)
   10951            4 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10952            4 :             .await.unwrap();
   10953            4 :         let child_timeline_id = tline_child.timeline_id;
   10954            4 :         Arc::try_unwrap(tline_child).unwrap();
   10955            4 : 
   10956            4 :         {
   10957            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10958            4 :             assert_eq!(
   10959            4 :                 gc_info_parent.retain_lsns,
   10960            4 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10961            4 :             );
   10962            4 :         }
   10963            4 : 
   10964            4 :         tenant
   10965            4 :             .get_offloaded_timeline(child_timeline_id)
   10966            4 :             .unwrap()
   10967            4 :             .defuse_for_tenant_drop();
   10968            4 : 
   10969            4 :         Ok(())
   10970            4 :     }
   10971              : 
   10972              :     #[cfg(feature = "testing")]
   10973              :     #[tokio::test]
   10974            4 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   10975            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   10976            4 :         let (tenant, ctx) = harness.load().await;
   10977            4 : 
   10978          592 :         fn get_key(id: u32) -> Key {
   10979          592 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10980          592 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10981          592 :             key.field6 = id;
   10982          592 :             key
   10983          592 :         }
   10984            4 : 
   10985            4 :         let img_layer = (0..10)
   10986           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10987            4 :             .collect_vec();
   10988            4 : 
   10989            4 :         let delta1 = vec![(
   10990            4 :             get_key(1),
   10991            4 :             Lsn(0x20),
   10992            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10993            4 :         )];
   10994            4 :         let delta4 = vec![(
   10995            4 :             get_key(1),
   10996            4 :             Lsn(0x28),
   10997            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10998            4 :         )];
   10999            4 :         let delta2 = vec![
   11000            4 :             (
   11001            4 :                 get_key(1),
   11002            4 :                 Lsn(0x30),
   11003            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11004            4 :             ),
   11005            4 :             (
   11006            4 :                 get_key(1),
   11007            4 :                 Lsn(0x38),
   11008            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11009            4 :             ),
   11010            4 :         ];
   11011            4 :         let delta3 = vec![
   11012            4 :             (
   11013            4 :                 get_key(8),
   11014            4 :                 Lsn(0x48),
   11015            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11016            4 :             ),
   11017            4 :             (
   11018            4 :                 get_key(9),
   11019            4 :                 Lsn(0x48),
   11020            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11021            4 :             ),
   11022            4 :         ];
   11023            4 : 
   11024            4 :         let tline = tenant
   11025            4 :             .create_test_timeline_with_layers(
   11026            4 :                 TIMELINE_ID,
   11027            4 :                 Lsn(0x10),
   11028            4 :                 DEFAULT_PG_VERSION,
   11029            4 :                 &ctx,
   11030            4 :                 vec![], // in-memory layers
   11031            4 :                 vec![
   11032            4 :                     // delta1/2/4 only contain a single key but multiple updates
   11033            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11034            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11035            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11036            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11037            4 :                 ], // delta layers
   11038            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11039            4 :                 Lsn(0x50),
   11040            4 :             )
   11041            4 :             .await?;
   11042            4 :         {
   11043            4 :             tline
   11044            4 :                 .applied_gc_cutoff_lsn
   11045            4 :                 .lock_for_write()
   11046            4 :                 .store_and_unlock(Lsn(0x30))
   11047            4 :                 .wait()
   11048            4 :                 .await;
   11049            4 :             // Update GC info
   11050            4 :             let mut guard = tline.gc_info.write().unwrap();
   11051            4 :             *guard = GcInfo {
   11052            4 :                 retain_lsns: vec![
   11053            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11054            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11055            4 :                 ],
   11056            4 :                 cutoffs: GcCutoffs {
   11057            4 :                     time: Lsn(0x30),
   11058            4 :                     space: Lsn(0x30),
   11059            4 :                 },
   11060            4 :                 leases: Default::default(),
   11061            4 :                 within_ancestor_pitr: false,
   11062            4 :             };
   11063            4 :         }
   11064            4 : 
   11065            4 :         let expected_result = [
   11066            4 :             Bytes::from_static(b"value 0@0x10"),
   11067            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11068            4 :             Bytes::from_static(b"value 2@0x10"),
   11069            4 :             Bytes::from_static(b"value 3@0x10"),
   11070            4 :             Bytes::from_static(b"value 4@0x10"),
   11071            4 :             Bytes::from_static(b"value 5@0x10"),
   11072            4 :             Bytes::from_static(b"value 6@0x10"),
   11073            4 :             Bytes::from_static(b"value 7@0x10"),
   11074            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11075            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11076            4 :         ];
   11077            4 : 
   11078            4 :         let expected_result_at_gc_horizon = [
   11079            4 :             Bytes::from_static(b"value 0@0x10"),
   11080            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11081            4 :             Bytes::from_static(b"value 2@0x10"),
   11082            4 :             Bytes::from_static(b"value 3@0x10"),
   11083            4 :             Bytes::from_static(b"value 4@0x10"),
   11084            4 :             Bytes::from_static(b"value 5@0x10"),
   11085            4 :             Bytes::from_static(b"value 6@0x10"),
   11086            4 :             Bytes::from_static(b"value 7@0x10"),
   11087            4 :             Bytes::from_static(b"value 8@0x10"),
   11088            4 :             Bytes::from_static(b"value 9@0x10"),
   11089            4 :         ];
   11090            4 : 
   11091            4 :         let expected_result_at_lsn_20 = [
   11092            4 :             Bytes::from_static(b"value 0@0x10"),
   11093            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11094            4 :             Bytes::from_static(b"value 2@0x10"),
   11095            4 :             Bytes::from_static(b"value 3@0x10"),
   11096            4 :             Bytes::from_static(b"value 4@0x10"),
   11097            4 :             Bytes::from_static(b"value 5@0x10"),
   11098            4 :             Bytes::from_static(b"value 6@0x10"),
   11099            4 :             Bytes::from_static(b"value 7@0x10"),
   11100            4 :             Bytes::from_static(b"value 8@0x10"),
   11101            4 :             Bytes::from_static(b"value 9@0x10"),
   11102            4 :         ];
   11103            4 : 
   11104            4 :         let expected_result_at_lsn_10 = [
   11105            4 :             Bytes::from_static(b"value 0@0x10"),
   11106            4 :             Bytes::from_static(b"value 1@0x10"),
   11107            4 :             Bytes::from_static(b"value 2@0x10"),
   11108            4 :             Bytes::from_static(b"value 3@0x10"),
   11109            4 :             Bytes::from_static(b"value 4@0x10"),
   11110            4 :             Bytes::from_static(b"value 5@0x10"),
   11111            4 :             Bytes::from_static(b"value 6@0x10"),
   11112            4 :             Bytes::from_static(b"value 7@0x10"),
   11113            4 :             Bytes::from_static(b"value 8@0x10"),
   11114            4 :             Bytes::from_static(b"value 9@0x10"),
   11115            4 :         ];
   11116            4 : 
   11117           12 :         let verify_result = || async {
   11118           12 :             let gc_horizon = {
   11119           12 :                 let gc_info = tline.gc_info.read().unwrap();
   11120           12 :                 gc_info.cutoffs.time
   11121            4 :             };
   11122          132 :             for idx in 0..10 {
   11123          120 :                 assert_eq!(
   11124          120 :                     tline
   11125          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11126          120 :                         .await
   11127          120 :                         .unwrap(),
   11128          120 :                     &expected_result[idx]
   11129            4 :                 );
   11130          120 :                 assert_eq!(
   11131          120 :                     tline
   11132          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11133          120 :                         .await
   11134          120 :                         .unwrap(),
   11135          120 :                     &expected_result_at_gc_horizon[idx]
   11136            4 :                 );
   11137          120 :                 assert_eq!(
   11138          120 :                     tline
   11139          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11140          120 :                         .await
   11141          120 :                         .unwrap(),
   11142          120 :                     &expected_result_at_lsn_20[idx]
   11143            4 :                 );
   11144          120 :                 assert_eq!(
   11145          120 :                     tline
   11146          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11147          120 :                         .await
   11148          120 :                         .unwrap(),
   11149          120 :                     &expected_result_at_lsn_10[idx]
   11150            4 :                 );
   11151            4 :             }
   11152           24 :         };
   11153            4 : 
   11154            4 :         verify_result().await;
   11155            4 : 
   11156            4 :         let cancel = CancellationToken::new();
   11157            4 :         tline
   11158            4 :             .compact_with_gc(
   11159            4 :                 &cancel,
   11160            4 :                 CompactOptions {
   11161            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   11162            4 :                     ..Default::default()
   11163            4 :                 },
   11164            4 :                 &ctx,
   11165            4 :             )
   11166            4 :             .await
   11167            4 :             .unwrap();
   11168            4 :         verify_result().await;
   11169            4 : 
   11170            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11171            4 :         check_layer_map_key_eq(
   11172            4 :             all_layers,
   11173            4 :             vec![
   11174            4 :                 // The original image layer, not compacted
   11175            4 :                 PersistentLayerKey {
   11176            4 :                     key_range: get_key(0)..get_key(10),
   11177            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11178            4 :                     is_delta: false,
   11179            4 :                 },
   11180            4 :                 // Delta layer below the specified above_lsn not compacted
   11181            4 :                 PersistentLayerKey {
   11182            4 :                     key_range: get_key(1)..get_key(2),
   11183            4 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   11184            4 :                     is_delta: true,
   11185            4 :                 },
   11186            4 :                 // Delta layer compacted above the LSN
   11187            4 :                 PersistentLayerKey {
   11188            4 :                     key_range: get_key(1)..get_key(10),
   11189            4 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   11190            4 :                     is_delta: true,
   11191            4 :                 },
   11192            4 :             ],
   11193            4 :         );
   11194            4 : 
   11195            4 :         // compact again
   11196            4 :         tline
   11197            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11198            4 :             .await
   11199            4 :             .unwrap();
   11200            4 :         verify_result().await;
   11201            4 : 
   11202            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11203            4 :         check_layer_map_key_eq(
   11204            4 :             all_layers,
   11205            4 :             vec![
   11206            4 :                 // The compacted image layer (full key range)
   11207            4 :                 PersistentLayerKey {
   11208            4 :                     key_range: Key::MIN..Key::MAX,
   11209            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11210            4 :                     is_delta: false,
   11211            4 :                 },
   11212            4 :                 // All other data in the delta layer
   11213            4 :                 PersistentLayerKey {
   11214            4 :                     key_range: get_key(1)..get_key(10),
   11215            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11216            4 :                     is_delta: true,
   11217            4 :                 },
   11218            4 :             ],
   11219            4 :         );
   11220            4 : 
   11221            4 :         Ok(())
   11222            4 :     }
   11223              : 
   11224              :     #[cfg(feature = "testing")]
   11225              :     #[tokio::test]
   11226            4 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   11227            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   11228            4 :         let (tenant, ctx) = harness.load().await;
   11229            4 : 
   11230         1016 :         fn get_key(id: u32) -> Key {
   11231         1016 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11232         1016 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11233         1016 :             key.field6 = id;
   11234         1016 :             key
   11235         1016 :         }
   11236            4 : 
   11237            4 :         let img_layer = (0..10)
   11238           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11239            4 :             .collect_vec();
   11240            4 : 
   11241            4 :         let delta1 = vec![(
   11242            4 :             get_key(1),
   11243            4 :             Lsn(0x20),
   11244            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11245            4 :         )];
   11246            4 :         let delta4 = vec![(
   11247            4 :             get_key(1),
   11248            4 :             Lsn(0x28),
   11249            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11250            4 :         )];
   11251            4 :         let delta2 = vec![
   11252            4 :             (
   11253            4 :                 get_key(1),
   11254            4 :                 Lsn(0x30),
   11255            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11256            4 :             ),
   11257            4 :             (
   11258            4 :                 get_key(1),
   11259            4 :                 Lsn(0x38),
   11260            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11261            4 :             ),
   11262            4 :         ];
   11263            4 :         let delta3 = vec![
   11264            4 :             (
   11265            4 :                 get_key(8),
   11266            4 :                 Lsn(0x48),
   11267            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11268            4 :             ),
   11269            4 :             (
   11270            4 :                 get_key(9),
   11271            4 :                 Lsn(0x48),
   11272            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11273            4 :             ),
   11274            4 :         ];
   11275            4 : 
   11276            4 :         let tline = tenant
   11277            4 :             .create_test_timeline_with_layers(
   11278            4 :                 TIMELINE_ID,
   11279            4 :                 Lsn(0x10),
   11280            4 :                 DEFAULT_PG_VERSION,
   11281            4 :                 &ctx,
   11282            4 :                 vec![], // in-memory layers
   11283            4 :                 vec![
   11284            4 :                     // delta1/2/4 only contain a single key but multiple updates
   11285            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11286            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11287            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11288            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11289            4 :                 ], // delta layers
   11290            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11291            4 :                 Lsn(0x50),
   11292            4 :             )
   11293            4 :             .await?;
   11294            4 :         {
   11295            4 :             tline
   11296            4 :                 .applied_gc_cutoff_lsn
   11297            4 :                 .lock_for_write()
   11298            4 :                 .store_and_unlock(Lsn(0x30))
   11299            4 :                 .wait()
   11300            4 :                 .await;
   11301            4 :             // Update GC info
   11302            4 :             let mut guard = tline.gc_info.write().unwrap();
   11303            4 :             *guard = GcInfo {
   11304            4 :                 retain_lsns: vec![
   11305            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11306            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11307            4 :                 ],
   11308            4 :                 cutoffs: GcCutoffs {
   11309            4 :                     time: Lsn(0x30),
   11310            4 :                     space: Lsn(0x30),
   11311            4 :                 },
   11312            4 :                 leases: Default::default(),
   11313            4 :                 within_ancestor_pitr: false,
   11314            4 :             };
   11315            4 :         }
   11316            4 : 
   11317            4 :         let expected_result = [
   11318            4 :             Bytes::from_static(b"value 0@0x10"),
   11319            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11320            4 :             Bytes::from_static(b"value 2@0x10"),
   11321            4 :             Bytes::from_static(b"value 3@0x10"),
   11322            4 :             Bytes::from_static(b"value 4@0x10"),
   11323            4 :             Bytes::from_static(b"value 5@0x10"),
   11324            4 :             Bytes::from_static(b"value 6@0x10"),
   11325            4 :             Bytes::from_static(b"value 7@0x10"),
   11326            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11327            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11328            4 :         ];
   11329            4 : 
   11330            4 :         let expected_result_at_gc_horizon = [
   11331            4 :             Bytes::from_static(b"value 0@0x10"),
   11332            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11333            4 :             Bytes::from_static(b"value 2@0x10"),
   11334            4 :             Bytes::from_static(b"value 3@0x10"),
   11335            4 :             Bytes::from_static(b"value 4@0x10"),
   11336            4 :             Bytes::from_static(b"value 5@0x10"),
   11337            4 :             Bytes::from_static(b"value 6@0x10"),
   11338            4 :             Bytes::from_static(b"value 7@0x10"),
   11339            4 :             Bytes::from_static(b"value 8@0x10"),
   11340            4 :             Bytes::from_static(b"value 9@0x10"),
   11341            4 :         ];
   11342            4 : 
   11343            4 :         let expected_result_at_lsn_20 = [
   11344            4 :             Bytes::from_static(b"value 0@0x10"),
   11345            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11346            4 :             Bytes::from_static(b"value 2@0x10"),
   11347            4 :             Bytes::from_static(b"value 3@0x10"),
   11348            4 :             Bytes::from_static(b"value 4@0x10"),
   11349            4 :             Bytes::from_static(b"value 5@0x10"),
   11350            4 :             Bytes::from_static(b"value 6@0x10"),
   11351            4 :             Bytes::from_static(b"value 7@0x10"),
   11352            4 :             Bytes::from_static(b"value 8@0x10"),
   11353            4 :             Bytes::from_static(b"value 9@0x10"),
   11354            4 :         ];
   11355            4 : 
   11356            4 :         let expected_result_at_lsn_10 = [
   11357            4 :             Bytes::from_static(b"value 0@0x10"),
   11358            4 :             Bytes::from_static(b"value 1@0x10"),
   11359            4 :             Bytes::from_static(b"value 2@0x10"),
   11360            4 :             Bytes::from_static(b"value 3@0x10"),
   11361            4 :             Bytes::from_static(b"value 4@0x10"),
   11362            4 :             Bytes::from_static(b"value 5@0x10"),
   11363            4 :             Bytes::from_static(b"value 6@0x10"),
   11364            4 :             Bytes::from_static(b"value 7@0x10"),
   11365            4 :             Bytes::from_static(b"value 8@0x10"),
   11366            4 :             Bytes::from_static(b"value 9@0x10"),
   11367            4 :         ];
   11368            4 : 
   11369           20 :         let verify_result = || async {
   11370           20 :             let gc_horizon = {
   11371           20 :                 let gc_info = tline.gc_info.read().unwrap();
   11372           20 :                 gc_info.cutoffs.time
   11373            4 :             };
   11374          220 :             for idx in 0..10 {
   11375          200 :                 assert_eq!(
   11376          200 :                     tline
   11377          200 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11378          200 :                         .await
   11379          200 :                         .unwrap(),
   11380          200 :                     &expected_result[idx]
   11381            4 :                 );
   11382          200 :                 assert_eq!(
   11383          200 :                     tline
   11384          200 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11385          200 :                         .await
   11386          200 :                         .unwrap(),
   11387          200 :                     &expected_result_at_gc_horizon[idx]
   11388            4 :                 );
   11389          200 :                 assert_eq!(
   11390          200 :                     tline
   11391          200 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11392          200 :                         .await
   11393          200 :                         .unwrap(),
   11394          200 :                     &expected_result_at_lsn_20[idx]
   11395            4 :                 );
   11396          200 :                 assert_eq!(
   11397          200 :                     tline
   11398          200 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11399          200 :                         .await
   11400          200 :                         .unwrap(),
   11401          200 :                     &expected_result_at_lsn_10[idx]
   11402            4 :                 );
   11403            4 :             }
   11404           40 :         };
   11405            4 : 
   11406            4 :         verify_result().await;
   11407            4 : 
   11408            4 :         let cancel = CancellationToken::new();
   11409            4 : 
   11410            4 :         tline
   11411            4 :             .compact_with_gc(
   11412            4 :                 &cancel,
   11413            4 :                 CompactOptions {
   11414            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11415            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   11416            4 :                     ..Default::default()
   11417            4 :                 },
   11418            4 :                 &ctx,
   11419            4 :             )
   11420            4 :             .await
   11421            4 :             .unwrap();
   11422            4 :         verify_result().await;
   11423            4 : 
   11424            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11425            4 :         check_layer_map_key_eq(
   11426            4 :             all_layers,
   11427            4 :             vec![
   11428            4 :                 // The original image layer, not compacted
   11429            4 :                 PersistentLayerKey {
   11430            4 :                     key_range: get_key(0)..get_key(10),
   11431            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11432            4 :                     is_delta: false,
   11433            4 :                 },
   11434            4 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   11435            4 :                 // the layer 0x28-0x30 into one.
   11436            4 :                 PersistentLayerKey {
   11437            4 :                     key_range: get_key(1)..get_key(2),
   11438            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11439            4 :                     is_delta: true,
   11440            4 :                 },
   11441            4 :                 // Above the upper bound and untouched
   11442            4 :                 PersistentLayerKey {
   11443            4 :                     key_range: get_key(1)..get_key(2),
   11444            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11445            4 :                     is_delta: true,
   11446            4 :                 },
   11447            4 :                 // This layer is untouched
   11448            4 :                 PersistentLayerKey {
   11449            4 :                     key_range: get_key(8)..get_key(10),
   11450            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11451            4 :                     is_delta: true,
   11452            4 :                 },
   11453            4 :             ],
   11454            4 :         );
   11455            4 : 
   11456            4 :         tline
   11457            4 :             .compact_with_gc(
   11458            4 :                 &cancel,
   11459            4 :                 CompactOptions {
   11460            4 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   11461            4 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   11462            4 :                     ..Default::default()
   11463            4 :                 },
   11464            4 :                 &ctx,
   11465            4 :             )
   11466            4 :             .await
   11467            4 :             .unwrap();
   11468            4 :         verify_result().await;
   11469            4 : 
   11470            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11471            4 :         check_layer_map_key_eq(
   11472            4 :             all_layers,
   11473            4 :             vec![
   11474            4 :                 // The original image layer, not compacted
   11475            4 :                 PersistentLayerKey {
   11476            4 :                     key_range: get_key(0)..get_key(10),
   11477            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11478            4 :                     is_delta: false,
   11479            4 :                 },
   11480            4 :                 // Not in the compaction key range, uncompacted
   11481            4 :                 PersistentLayerKey {
   11482            4 :                     key_range: get_key(1)..get_key(2),
   11483            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11484            4 :                     is_delta: true,
   11485            4 :                 },
   11486            4 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   11487            4 :                 PersistentLayerKey {
   11488            4 :                     key_range: get_key(1)..get_key(2),
   11489            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11490            4 :                     is_delta: true,
   11491            4 :                 },
   11492            4 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   11493            4 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   11494            4 :                 // becomes 0x50.
   11495            4 :                 PersistentLayerKey {
   11496            4 :                     key_range: get_key(8)..get_key(10),
   11497            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11498            4 :                     is_delta: true,
   11499            4 :                 },
   11500            4 :             ],
   11501            4 :         );
   11502            4 : 
   11503            4 :         // compact again
   11504            4 :         tline
   11505            4 :             .compact_with_gc(
   11506            4 :                 &cancel,
   11507            4 :                 CompactOptions {
   11508            4 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   11509            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   11510            4 :                     ..Default::default()
   11511            4 :                 },
   11512            4 :                 &ctx,
   11513            4 :             )
   11514            4 :             .await
   11515            4 :             .unwrap();
   11516            4 :         verify_result().await;
   11517            4 : 
   11518            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11519            4 :         check_layer_map_key_eq(
   11520            4 :             all_layers,
   11521            4 :             vec![
   11522            4 :                 // The original image layer, not compacted
   11523            4 :                 PersistentLayerKey {
   11524            4 :                     key_range: get_key(0)..get_key(10),
   11525            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11526            4 :                     is_delta: false,
   11527            4 :                 },
   11528            4 :                 // The range gets compacted
   11529            4 :                 PersistentLayerKey {
   11530            4 :                     key_range: get_key(1)..get_key(2),
   11531            4 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   11532            4 :                     is_delta: true,
   11533            4 :                 },
   11534            4 :                 // Not touched during this iteration of compaction
   11535            4 :                 PersistentLayerKey {
   11536            4 :                     key_range: get_key(8)..get_key(10),
   11537            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11538            4 :                     is_delta: true,
   11539            4 :                 },
   11540            4 :             ],
   11541            4 :         );
   11542            4 : 
   11543            4 :         // final full compaction
   11544            4 :         tline
   11545            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11546            4 :             .await
   11547            4 :             .unwrap();
   11548            4 :         verify_result().await;
   11549            4 : 
   11550            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11551            4 :         check_layer_map_key_eq(
   11552            4 :             all_layers,
   11553            4 :             vec![
   11554            4 :                 // The compacted image layer (full key range)
   11555            4 :                 PersistentLayerKey {
   11556            4 :                     key_range: Key::MIN..Key::MAX,
   11557            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11558            4 :                     is_delta: false,
   11559            4 :                 },
   11560            4 :                 // All other data in the delta layer
   11561            4 :                 PersistentLayerKey {
   11562            4 :                     key_range: get_key(1)..get_key(10),
   11563            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11564            4 :                     is_delta: true,
   11565            4 :                 },
   11566            4 :             ],
   11567            4 :         );
   11568            4 : 
   11569            4 :         Ok(())
   11570            4 :     }
   11571              : }
        

Generated by: LCOV version 2.1-beta