LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: feead26e04cdef6e988ff1765b1cb7075eb48d3d.info Lines: 75.9 % 8608 6536
Test Date: 2025-02-28 12:11:00 Functions: 59.5 % 449 267

            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              : use pageserver_api::models;
      35              : pub use pageserver_api::models::TenantState;
      36              : use pageserver_api::models::{
      37              :     CompactInfoResponse, LsnLease, TimelineArchivalState, TimelineState, TopTenantShardItem,
      38              :     WalRedoManagerStatus,
      39              : };
      40              : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
      41              : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
      42              : use remote_timeline_client::index::GcCompactionState;
      43              : use remote_timeline_client::manifest::{
      44              :     LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
      45              : };
      46              : use remote_timeline_client::{
      47              :     FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
      48              : };
      49              : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
      50              : use storage_broker::BrokerClientChannel;
      51              : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
      52              : use timeline::offload::{OffloadError, offload_timeline};
      53              : use timeline::{
      54              :     CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
      55              : };
      56              : use tokio::io::BufReader;
      57              : use tokio::sync::{Notify, Semaphore, watch};
      58              : use tokio::task::JoinSet;
      59              : use tokio_util::sync::CancellationToken;
      60              : use tracing::*;
      61              : use upload_queue::NotInitialized;
      62              : use utils::circuit_breaker::CircuitBreaker;
      63              : use utils::crashsafe::path_with_suffix_extension;
      64              : use utils::sync::gate::{Gate, GateGuard};
      65              : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
      66              : use utils::try_rcu::ArcSwapExt;
      67              : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
      68              : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
      69              : 
      70              : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf, TenantConf};
      71              : use self::metadata::TimelineMetadata;
      72              : use self::mgr::{GetActiveTenantError, GetTenantError};
      73              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      74              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      75              : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
      76              : use self::timeline::{
      77              :     EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
      78              : };
      79              : use crate::config::PageServerConf;
      80              : use crate::context::{DownloadBehavior, RequestContext};
      81              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
      82              : use crate::l0_flush::L0FlushGlobalState;
      83              : use crate::metrics::{
      84              :     BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
      85              :     INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_STATE_METRIC,
      86              :     TENANT_SYNTHETIC_SIZE_METRIC, remove_tenant_metrics,
      87              : };
      88              : use crate::task_mgr::TaskKind;
      89              : use crate::tenant::config::{LocationMode, TenantConfOpt};
      90              : use crate::tenant::gc_result::GcResult;
      91              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
      92              : use crate::tenant::remote_timeline_client::{
      93              :     INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
      94              : };
      95              : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
      96              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
      97              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
      98              : use crate::virtual_file::VirtualFile;
      99              : use crate::walingest::WalLagCooldown;
     100              : use crate::walredo::PostgresRedoManager;
     101              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
     102              : 
     103            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     104              : use utils::crashsafe;
     105              : use utils::generation::Generation;
     106              : use utils::id::TimelineId;
     107              : use utils::lsn::{Lsn, RecordLsn};
     108              : 
     109              : pub mod blob_io;
     110              : pub mod block_io;
     111              : pub mod vectored_blob_io;
     112              : 
     113              : pub mod disk_btree;
     114              : pub(crate) mod ephemeral_file;
     115              : pub mod layer_map;
     116              : 
     117              : pub mod metadata;
     118              : pub mod remote_timeline_client;
     119              : pub mod storage_layer;
     120              : 
     121              : pub mod checks;
     122              : pub mod config;
     123              : pub mod mgr;
     124              : pub mod secondary;
     125              : pub mod tasks;
     126              : pub mod upload_queue;
     127              : 
     128              : pub(crate) mod timeline;
     129              : 
     130              : pub mod size;
     131              : 
     132              : mod gc_block;
     133              : mod gc_result;
     134              : pub(crate) mod throttle;
     135              : 
     136              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     137              : 
     138              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     139              : // re-export for use in walreceiver
     140              : pub use crate::tenant::timeline::WalReceiverInfo;
     141              : 
     142              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     143              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     144              : 
     145              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     146              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     147              : 
     148              : /// References to shared objects that are passed into each tenant, such
     149              : /// as the shared remote storage client and process initialization state.
     150              : #[derive(Clone)]
     151              : pub struct TenantSharedResources {
     152              :     pub broker_client: storage_broker::BrokerClientChannel,
     153              :     pub remote_storage: GenericRemoteStorage,
     154              :     pub deletion_queue_client: DeletionQueueClient,
     155              :     pub l0_flush_global_state: L0FlushGlobalState,
     156              : }
     157              : 
     158              : /// A [`Tenant`] is really an _attached_ tenant.  The configuration
     159              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     160              : /// in this struct.
     161              : #[derive(Clone)]
     162              : pub(super) struct AttachedTenantConf {
     163              :     tenant_conf: TenantConfOpt,
     164              :     location: AttachedLocationConfig,
     165              :     /// The deadline before which we are blocked from GC so that
     166              :     /// leases have a chance to be renewed.
     167              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     168              : }
     169              : 
     170              : impl AttachedTenantConf {
     171          444 :     fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
     172              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     173              :         //
     174              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     175              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     176              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     177          444 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     178          444 :             Some(
     179          444 :                 tokio::time::Instant::now()
     180          444 :                     + tenant_conf
     181          444 :                         .lsn_lease_length
     182          444 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     183          444 :             )
     184              :         } else {
     185              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     186              :             // because we don't do GC in these modes.
     187            0 :             None
     188              :         };
     189              : 
     190          444 :         Self {
     191          444 :             tenant_conf,
     192          444 :             location,
     193          444 :             lsn_lease_deadline,
     194          444 :         }
     195          444 :     }
     196              : 
     197          444 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     198          444 :         match &location_conf.mode {
     199          444 :             LocationMode::Attached(attach_conf) => {
     200          444 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     201              :             }
     202              :             LocationMode::Secondary(_) => {
     203            0 :                 anyhow::bail!(
     204            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     205            0 :                 )
     206              :             }
     207              :         }
     208          444 :     }
     209              : 
     210         1524 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     211         1524 :         self.lsn_lease_deadline
     212         1524 :             .map(|d| tokio::time::Instant::now() < d)
     213         1524 :             .unwrap_or(false)
     214         1524 :     }
     215              : }
     216              : struct TimelinePreload {
     217              :     timeline_id: TimelineId,
     218              :     client: RemoteTimelineClient,
     219              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     220              :     previous_heatmap: Option<PreviousHeatmap>,
     221              : }
     222              : 
     223              : pub(crate) struct TenantPreload {
     224              :     tenant_manifest: TenantManifest,
     225              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     226              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     227              : }
     228              : 
     229              : /// When we spawn a tenant, there is a special mode for tenant creation that
     230              : /// avoids trying to read anything from remote storage.
     231              : pub(crate) enum SpawnMode {
     232              :     /// Activate as soon as possible
     233              :     Eager,
     234              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     235              :     Lazy,
     236              : }
     237              : 
     238              : ///
     239              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     240              : ///
     241              : pub struct Tenant {
     242              :     // Global pageserver config parameters
     243              :     pub conf: &'static PageServerConf,
     244              : 
     245              :     /// The value creation timestamp, used to measure activation delay, see:
     246              :     /// <https://github.com/neondatabase/neon/issues/4025>
     247              :     constructed_at: Instant,
     248              : 
     249              :     state: watch::Sender<TenantState>,
     250              : 
     251              :     // Overridden tenant-specific config parameters.
     252              :     // We keep TenantConfOpt sturct here to preserve the information
     253              :     // about parameters that are not set.
     254              :     // This is necessary to allow global config updates.
     255              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     256              : 
     257              :     tenant_shard_id: TenantShardId,
     258              : 
     259              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     260              :     shard_identity: ShardIdentity,
     261              : 
     262              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     263              :     /// Does not change over the lifetime of the [`Tenant`] object.
     264              :     ///
     265              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     266              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     267              :     generation: Generation,
     268              : 
     269              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     270              : 
     271              :     /// During timeline creation, we first insert the TimelineId to the
     272              :     /// creating map, then `timelines`, then remove it from the creating map.
     273              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     274              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     275              : 
     276              :     /// Possibly offloaded and archived timelines
     277              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     278              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     279              : 
     280              :     /// Serialize writes of the tenant manifest to remote storage.  If there are concurrent operations
     281              :     /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
     282              :     /// each other (this could be optimized to coalesce writes if necessary).
     283              :     ///
     284              :     /// The contents of the Mutex are the last manifest we successfully uploaded
     285              :     tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
     286              : 
     287              :     // This mutex prevents creation of new timelines during GC.
     288              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     289              :     // `timelines` mutex during all GC iteration
     290              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     291              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     292              :     // timeout...
     293              :     gc_cs: tokio::sync::Mutex<()>,
     294              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     295              : 
     296              :     // provides access to timeline data sitting in the remote storage
     297              :     pub(crate) remote_storage: GenericRemoteStorage,
     298              : 
     299              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     300              :     deletion_queue_client: DeletionQueueClient,
     301              : 
     302              :     /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
     303              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     304              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     305              : 
     306              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     307              : 
     308              :     /// Track repeated failures to compact, so that we can back off.
     309              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     310              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     311              : 
     312              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     313              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     314              : 
     315              :     /// Scheduled gc-compaction tasks.
     316              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     317              : 
     318              :     /// If the tenant is in Activating state, notify this to encourage it
     319              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     320              :     /// background warmup.
     321              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     322              : 
     323              :     /// Time it took for the tenant to activate. Zero if not active yet.
     324              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     325              : 
     326              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     327              :     // Timelines' cancellation token.
     328              :     pub(crate) cancel: CancellationToken,
     329              : 
     330              :     // Users of the Tenant such as the page service must take this Gate to avoid
     331              :     // trying to use a Tenant which is shutting down.
     332              :     pub(crate) gate: Gate,
     333              : 
     334              :     /// Throttle applied at the top of [`Timeline::get`].
     335              :     /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
     336              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     337              : 
     338              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     339              : 
     340              :     /// An ongoing timeline detach concurrency limiter.
     341              :     ///
     342              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     343              :     /// to have two running at the same time. A different one can be started if an earlier one
     344              :     /// has failed for whatever reason.
     345              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     346              : 
     347              :     /// `index_part.json` based gc blocking reason tracking.
     348              :     ///
     349              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     350              :     /// proceeding.
     351              :     pub(crate) gc_block: gc_block::GcBlock,
     352              : 
     353              :     l0_flush_global_state: L0FlushGlobalState,
     354              : }
     355              : impl std::fmt::Debug for Tenant {
     356            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     357            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     358            0 :     }
     359              : }
     360              : 
     361              : pub(crate) enum WalRedoManager {
     362              :     Prod(WalredoManagerId, PostgresRedoManager),
     363              :     #[cfg(test)]
     364              :     Test(harness::TestRedoManager),
     365              : }
     366              : 
     367              : #[derive(thiserror::Error, Debug)]
     368              : #[error("pageserver is shutting down")]
     369              : pub(crate) struct GlobalShutDown;
     370              : 
     371              : impl WalRedoManager {
     372            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     373            0 :         let id = WalredoManagerId::next();
     374            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     375            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     376            0 :         match &mut *guard {
     377            0 :             Some(map) => {
     378            0 :                 map.insert(id, Arc::downgrade(&arc));
     379            0 :                 Ok(arc)
     380              :             }
     381            0 :             None => Err(GlobalShutDown),
     382              :         }
     383            0 :     }
     384              : }
     385              : 
     386              : impl Drop for WalRedoManager {
     387           20 :     fn drop(&mut self) {
     388           20 :         match self {
     389            0 :             Self::Prod(id, _) => {
     390            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     391            0 :                 if let Some(map) = &mut *guard {
     392            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     393            0 :                 }
     394              :             }
     395              :             #[cfg(test)]
     396           20 :             Self::Test(_) => {
     397           20 :                 // Not applicable to test redo manager
     398           20 :             }
     399              :         }
     400           20 :     }
     401              : }
     402              : 
     403              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     404              : /// the walredo processes outside of the regular order.
     405              : ///
     406              : /// This is necessary to work around a systemd bug where it freezes if there are
     407              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     408              : #[allow(clippy::type_complexity)]
     409              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     410              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     411            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     412              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     413              : pub(crate) struct WalredoManagerId(u64);
     414              : impl WalredoManagerId {
     415            0 :     pub fn next() -> Self {
     416              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     417            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     418            0 :         if id == 0 {
     419            0 :             panic!(
     420            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     421            0 :             );
     422            0 :         }
     423            0 :         Self(id)
     424            0 :     }
     425              : }
     426              : 
     427              : #[cfg(test)]
     428              : impl From<harness::TestRedoManager> for WalRedoManager {
     429          444 :     fn from(mgr: harness::TestRedoManager) -> Self {
     430          444 :         Self::Test(mgr)
     431          444 :     }
     432              : }
     433              : 
     434              : impl WalRedoManager {
     435           12 :     pub(crate) async fn shutdown(&self) -> bool {
     436           12 :         match self {
     437            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     438              :             #[cfg(test)]
     439              :             Self::Test(_) => {
     440              :                 // Not applicable to test redo manager
     441           12 :                 true
     442              :             }
     443              :         }
     444           12 :     }
     445              : 
     446            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     447            0 :         match self {
     448            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     449            0 :             #[cfg(test)]
     450            0 :             Self::Test(_) => {
     451            0 :                 // Not applicable to test redo manager
     452            0 :             }
     453            0 :         }
     454            0 :     }
     455              : 
     456              :     /// # Cancel-Safety
     457              :     ///
     458              :     /// This method is cancellation-safe.
     459         1636 :     pub async fn request_redo(
     460         1636 :         &self,
     461         1636 :         key: pageserver_api::key::Key,
     462         1636 :         lsn: Lsn,
     463         1636 :         base_img: Option<(Lsn, bytes::Bytes)>,
     464         1636 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     465         1636 :         pg_version: u32,
     466         1636 :     ) -> Result<bytes::Bytes, walredo::Error> {
     467         1636 :         match self {
     468            0 :             Self::Prod(_, mgr) => {
     469            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     470            0 :                     .await
     471              :             }
     472              :             #[cfg(test)]
     473         1636 :             Self::Test(mgr) => {
     474         1636 :                 mgr.request_redo(key, lsn, base_img, records, pg_version)
     475         1636 :                     .await
     476              :             }
     477              :         }
     478         1636 :     }
     479              : 
     480            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     481            0 :         match self {
     482            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     483            0 :             #[cfg(test)]
     484            0 :             WalRedoManager::Test(_) => None,
     485            0 :         }
     486            0 :     }
     487              : }
     488              : 
     489              : /// A very lightweight memory representation of an offloaded timeline.
     490              : ///
     491              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     492              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     493              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     494              : /// more offloaded timelines than we can manage ones that aren't.
     495              : pub struct OffloadedTimeline {
     496              :     pub tenant_shard_id: TenantShardId,
     497              :     pub timeline_id: TimelineId,
     498              :     pub ancestor_timeline_id: Option<TimelineId>,
     499              :     /// Whether to retain the branch lsn at the ancestor or not
     500              :     pub ancestor_retain_lsn: Option<Lsn>,
     501              : 
     502              :     /// When the timeline was archived.
     503              :     ///
     504              :     /// Present for future flattening deliberations.
     505              :     pub archived_at: NaiveDateTime,
     506              : 
     507              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     508              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     509              :     pub delete_progress: TimelineDeleteProgress,
     510              : 
     511              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     512              :     pub deleted_from_ancestor: AtomicBool,
     513              : }
     514              : 
     515              : impl OffloadedTimeline {
     516              :     /// Obtains an offloaded timeline from a given timeline object.
     517              :     ///
     518              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     519              :     /// the timeline is not in a stopped state.
     520              :     /// Panics if the timeline is not archived.
     521            4 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     522            4 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     523            4 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     524            4 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     525            4 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     526            4 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     527            4 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     528            4 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     529              :             } else {
     530            0 :                 (None, None)
     531              :             };
     532            4 :         let archived_at = timeline
     533            4 :             .remote_client
     534            4 :             .archived_at_stopped_queue()?
     535            4 :             .expect("must be called on an archived timeline");
     536            4 :         Ok(Self {
     537            4 :             tenant_shard_id: timeline.tenant_shard_id,
     538            4 :             timeline_id: timeline.timeline_id,
     539            4 :             ancestor_timeline_id,
     540            4 :             ancestor_retain_lsn,
     541            4 :             archived_at,
     542            4 : 
     543            4 :             delete_progress: timeline.delete_progress.clone(),
     544            4 :             deleted_from_ancestor: AtomicBool::new(false),
     545            4 :         })
     546            4 :     }
     547            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     548            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     549            0 :         // by the `initialize_gc_info` function.
     550            0 :         let OffloadedTimelineManifest {
     551            0 :             timeline_id,
     552            0 :             ancestor_timeline_id,
     553            0 :             ancestor_retain_lsn,
     554            0 :             archived_at,
     555            0 :         } = *manifest;
     556            0 :         Self {
     557            0 :             tenant_shard_id,
     558            0 :             timeline_id,
     559            0 :             ancestor_timeline_id,
     560            0 :             ancestor_retain_lsn,
     561            0 :             archived_at,
     562            0 :             delete_progress: TimelineDeleteProgress::default(),
     563            0 :             deleted_from_ancestor: AtomicBool::new(false),
     564            0 :         }
     565            0 :     }
     566            4 :     fn manifest(&self) -> OffloadedTimelineManifest {
     567            4 :         let Self {
     568            4 :             timeline_id,
     569            4 :             ancestor_timeline_id,
     570            4 :             ancestor_retain_lsn,
     571            4 :             archived_at,
     572            4 :             ..
     573            4 :         } = self;
     574            4 :         OffloadedTimelineManifest {
     575            4 :             timeline_id: *timeline_id,
     576            4 :             ancestor_timeline_id: *ancestor_timeline_id,
     577            4 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     578            4 :             archived_at: *archived_at,
     579            4 :         }
     580            4 :     }
     581              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     582            0 :     fn delete_from_ancestor_with_timelines(
     583            0 :         &self,
     584            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     585            0 :     ) {
     586            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     587            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     588              :         {
     589            0 :             if let Some((_, ancestor_timeline)) = timelines
     590            0 :                 .iter()
     591            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     592              :             {
     593            0 :                 let removal_happened = ancestor_timeline
     594            0 :                     .gc_info
     595            0 :                     .write()
     596            0 :                     .unwrap()
     597            0 :                     .remove_child_offloaded(self.timeline_id);
     598            0 :                 if !removal_happened {
     599            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     600            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     601            0 :                 }
     602            0 :             }
     603            0 :         }
     604            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     605            0 :     }
     606              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     607              :     ///
     608              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     609            4 :     fn defuse_for_tenant_drop(&self) {
     610            4 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     611            4 :     }
     612              : }
     613              : 
     614              : impl fmt::Debug for OffloadedTimeline {
     615            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     616            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     617            0 :     }
     618              : }
     619              : 
     620              : impl Drop for OffloadedTimeline {
     621            4 :     fn drop(&mut self) {
     622            4 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     623            0 :             tracing::warn!(
     624            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     625              :                 self.timeline_id
     626              :             );
     627            4 :         }
     628            4 :     }
     629              : }
     630              : 
     631              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     632              : pub enum MaybeOffloaded {
     633              :     Yes,
     634              :     No,
     635              : }
     636              : 
     637              : #[derive(Clone, Debug)]
     638              : pub enum TimelineOrOffloaded {
     639              :     Timeline(Arc<Timeline>),
     640              :     Offloaded(Arc<OffloadedTimeline>),
     641              : }
     642              : 
     643              : impl TimelineOrOffloaded {
     644            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     645            0 :         match self {
     646            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     647            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     648              :             }
     649            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     650            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     651              :             }
     652              :         }
     653            0 :     }
     654            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     655            0 :         self.arc_ref().tenant_shard_id()
     656            0 :     }
     657            0 :     pub fn timeline_id(&self) -> TimelineId {
     658            0 :         self.arc_ref().timeline_id()
     659            0 :     }
     660            4 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     661            4 :         match self {
     662            4 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     663            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     664              :         }
     665            4 :     }
     666            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     667            0 :         match self {
     668            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     669            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     670              :         }
     671            0 :     }
     672              : }
     673              : 
     674              : pub enum TimelineOrOffloadedArcRef<'a> {
     675              :     Timeline(&'a Arc<Timeline>),
     676              :     Offloaded(&'a Arc<OffloadedTimeline>),
     677              : }
     678              : 
     679              : impl TimelineOrOffloadedArcRef<'_> {
     680            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     681            0 :         match self {
     682            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     683            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     684              :         }
     685            0 :     }
     686            0 :     pub fn timeline_id(&self) -> TimelineId {
     687            0 :         match self {
     688            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     689            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     690              :         }
     691            0 :     }
     692              : }
     693              : 
     694              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     695            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     696            0 :         Self::Timeline(timeline)
     697            0 :     }
     698              : }
     699              : 
     700              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     701            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     702            0 :         Self::Offloaded(timeline)
     703            0 :     }
     704              : }
     705              : 
     706              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     707              : pub enum GetTimelineError {
     708              :     #[error("Timeline is shutting down")]
     709              :     ShuttingDown,
     710              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     711              :     NotActive {
     712              :         tenant_id: TenantShardId,
     713              :         timeline_id: TimelineId,
     714              :         state: TimelineState,
     715              :     },
     716              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     717              :     NotFound {
     718              :         tenant_id: TenantShardId,
     719              :         timeline_id: TimelineId,
     720              :     },
     721              : }
     722              : 
     723              : #[derive(Debug, thiserror::Error)]
     724              : pub enum LoadLocalTimelineError {
     725              :     #[error("FailedToLoad")]
     726              :     Load(#[source] anyhow::Error),
     727              :     #[error("FailedToResumeDeletion")]
     728              :     ResumeDeletion(#[source] anyhow::Error),
     729              : }
     730              : 
     731              : #[derive(thiserror::Error)]
     732              : pub enum DeleteTimelineError {
     733              :     #[error("NotFound")]
     734              :     NotFound,
     735              : 
     736              :     #[error("HasChildren")]
     737              :     HasChildren(Vec<TimelineId>),
     738              : 
     739              :     #[error("Timeline deletion is already in progress")]
     740              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     741              : 
     742              :     #[error("Cancelled")]
     743              :     Cancelled,
     744              : 
     745              :     #[error(transparent)]
     746              :     Other(#[from] anyhow::Error),
     747              : }
     748              : 
     749              : impl Debug for DeleteTimelineError {
     750            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     751            0 :         match self {
     752            0 :             Self::NotFound => write!(f, "NotFound"),
     753            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     754            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     755            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     756            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     757              :         }
     758            0 :     }
     759              : }
     760              : 
     761              : #[derive(thiserror::Error)]
     762              : pub enum TimelineArchivalError {
     763              :     #[error("NotFound")]
     764              :     NotFound,
     765              : 
     766              :     #[error("Timeout")]
     767              :     Timeout,
     768              : 
     769              :     #[error("Cancelled")]
     770              :     Cancelled,
     771              : 
     772              :     #[error("ancestor is archived: {}", .0)]
     773              :     HasArchivedParent(TimelineId),
     774              : 
     775              :     #[error("HasUnarchivedChildren")]
     776              :     HasUnarchivedChildren(Vec<TimelineId>),
     777              : 
     778              :     #[error("Timeline archival is already in progress")]
     779              :     AlreadyInProgress,
     780              : 
     781              :     #[error(transparent)]
     782              :     Other(anyhow::Error),
     783              : }
     784              : 
     785              : #[derive(thiserror::Error, Debug)]
     786              : pub(crate) enum TenantManifestError {
     787              :     #[error("Remote storage error: {0}")]
     788              :     RemoteStorage(anyhow::Error),
     789              : 
     790              :     #[error("Cancelled")]
     791              :     Cancelled,
     792              : }
     793              : 
     794              : impl From<TenantManifestError> for TimelineArchivalError {
     795            0 :     fn from(e: TenantManifestError) -> Self {
     796            0 :         match e {
     797            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     798            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     799              :         }
     800            0 :     }
     801              : }
     802              : 
     803              : impl Debug for TimelineArchivalError {
     804            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     805            0 :         match self {
     806            0 :             Self::NotFound => write!(f, "NotFound"),
     807            0 :             Self::Timeout => write!(f, "Timeout"),
     808            0 :             Self::Cancelled => write!(f, "Cancelled"),
     809            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     810            0 :             Self::HasUnarchivedChildren(c) => {
     811            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     812              :             }
     813            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     814            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     815              :         }
     816            0 :     }
     817              : }
     818              : 
     819              : pub enum SetStoppingError {
     820              :     AlreadyStopping(completion::Barrier),
     821              :     Broken,
     822              : }
     823              : 
     824              : impl Debug for SetStoppingError {
     825            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     826            0 :         match self {
     827            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     828            0 :             Self::Broken => write!(f, "Broken"),
     829              :         }
     830            0 :     }
     831              : }
     832              : 
     833              : /// Arguments to [`Tenant::create_timeline`].
     834              : ///
     835              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     836              : /// is `None`, the result of the timeline create call is not deterministic.
     837              : ///
     838              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     839              : #[derive(Debug)]
     840              : pub(crate) enum CreateTimelineParams {
     841              :     Bootstrap(CreateTimelineParamsBootstrap),
     842              :     Branch(CreateTimelineParamsBranch),
     843              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     844              : }
     845              : 
     846              : #[derive(Debug)]
     847              : pub(crate) struct CreateTimelineParamsBootstrap {
     848              :     pub(crate) new_timeline_id: TimelineId,
     849              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     850              :     pub(crate) pg_version: u32,
     851              : }
     852              : 
     853              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     854              : #[derive(Debug)]
     855              : pub(crate) struct CreateTimelineParamsBranch {
     856              :     pub(crate) new_timeline_id: TimelineId,
     857              :     pub(crate) ancestor_timeline_id: TimelineId,
     858              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     859              : }
     860              : 
     861              : #[derive(Debug)]
     862              : pub(crate) struct CreateTimelineParamsImportPgdata {
     863              :     pub(crate) new_timeline_id: TimelineId,
     864              :     pub(crate) location: import_pgdata::index_part_format::Location,
     865              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     866              : }
     867              : 
     868              : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in  [`Tenant::start_creating_timeline`] in  [`Tenant::start_creating_timeline`].
     869              : ///
     870              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     871              : ///
     872              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     873              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     874              : ///
     875              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     876              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     877              : ///
     878              : /// Notes:
     879              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     880              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     881              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     882              : ///
     883              : #[derive(Debug, Clone, PartialEq, Eq)]
     884              : pub(crate) enum CreateTimelineIdempotency {
     885              :     /// NB: special treatment, see comment in [`Self`].
     886              :     FailWithConflict,
     887              :     Bootstrap {
     888              :         pg_version: u32,
     889              :     },
     890              :     /// NB: branches always have the same `pg_version` as their ancestor.
     891              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     892              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     893              :     /// determining the child branch pg_version.
     894              :     Branch {
     895              :         ancestor_timeline_id: TimelineId,
     896              :         ancestor_start_lsn: Lsn,
     897              :     },
     898              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     899              : }
     900              : 
     901              : #[derive(Debug, Clone, PartialEq, Eq)]
     902              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     903              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     904              : }
     905              : 
     906              : /// What is returned by [`Tenant::start_creating_timeline`].
     907              : #[must_use]
     908              : enum StartCreatingTimelineResult {
     909              :     CreateGuard(TimelineCreateGuard),
     910              :     Idempotent(Arc<Timeline>),
     911              : }
     912              : 
     913              : enum TimelineInitAndSyncResult {
     914              :     ReadyToActivate(Arc<Timeline>),
     915              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     916              : }
     917              : 
     918              : impl TimelineInitAndSyncResult {
     919            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     920            0 :         match self {
     921            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     922            0 :             _ => None,
     923              :         }
     924            0 :     }
     925              : }
     926              : 
     927              : #[must_use]
     928              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     929              :     timeline: Arc<Timeline>,
     930              :     import_pgdata: import_pgdata::index_part_format::Root,
     931              :     guard: TimelineCreateGuard,
     932              : }
     933              : 
     934              : /// What is returned by [`Tenant::create_timeline`].
     935              : enum CreateTimelineResult {
     936              :     Created(Arc<Timeline>),
     937              :     Idempotent(Arc<Timeline>),
     938              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
     939              :     /// we return this result, nor will this concrete object ever be added there.
     940              :     /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
     941              :     ImportSpawned(Arc<Timeline>),
     942              : }
     943              : 
     944              : impl CreateTimelineResult {
     945            0 :     fn discriminant(&self) -> &'static str {
     946            0 :         match self {
     947            0 :             Self::Created(_) => "Created",
     948            0 :             Self::Idempotent(_) => "Idempotent",
     949            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     950              :         }
     951            0 :     }
     952            0 :     fn timeline(&self) -> &Arc<Timeline> {
     953            0 :         match self {
     954            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     955            0 :         }
     956            0 :     }
     957              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     958              :     #[cfg(test)]
     959          460 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     960          460 :         match self {
     961          460 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     962          460 :         }
     963          460 :     }
     964              : }
     965              : 
     966              : #[derive(thiserror::Error, Debug)]
     967              : pub enum CreateTimelineError {
     968              :     #[error("creation of timeline with the given ID is in progress")]
     969              :     AlreadyCreating,
     970              :     #[error("timeline already exists with different parameters")]
     971              :     Conflict,
     972              :     #[error(transparent)]
     973              :     AncestorLsn(anyhow::Error),
     974              :     #[error("ancestor timeline is not active")]
     975              :     AncestorNotActive,
     976              :     #[error("ancestor timeline is archived")]
     977              :     AncestorArchived,
     978              :     #[error("tenant shutting down")]
     979              :     ShuttingDown,
     980              :     #[error(transparent)]
     981              :     Other(#[from] anyhow::Error),
     982              : }
     983              : 
     984              : #[derive(thiserror::Error, Debug)]
     985              : pub enum InitdbError {
     986              :     #[error("Operation was cancelled")]
     987              :     Cancelled,
     988              :     #[error(transparent)]
     989              :     Other(anyhow::Error),
     990              :     #[error(transparent)]
     991              :     Inner(postgres_initdb::Error),
     992              : }
     993              : 
     994              : enum CreateTimelineCause {
     995              :     Load,
     996              :     Delete,
     997              : }
     998              : 
     999              : enum LoadTimelineCause {
    1000              :     Attach,
    1001              :     Unoffload,
    1002              :     ImportPgdata {
    1003              :         create_guard: TimelineCreateGuard,
    1004              :         activate: ActivateTimelineArgs,
    1005              :     },
    1006              : }
    1007              : 
    1008              : #[derive(thiserror::Error, Debug)]
    1009              : pub(crate) enum GcError {
    1010              :     // The tenant is shutting down
    1011              :     #[error("tenant shutting down")]
    1012              :     TenantCancelled,
    1013              : 
    1014              :     // The tenant is shutting down
    1015              :     #[error("timeline shutting down")]
    1016              :     TimelineCancelled,
    1017              : 
    1018              :     // The tenant is in a state inelegible to run GC
    1019              :     #[error("not active")]
    1020              :     NotActive,
    1021              : 
    1022              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1023              :     #[error("not active")]
    1024              :     BadLsn { why: String },
    1025              : 
    1026              :     // A remote storage error while scheduling updates after compaction
    1027              :     #[error(transparent)]
    1028              :     Remote(anyhow::Error),
    1029              : 
    1030              :     // An error reading while calculating GC cutoffs
    1031              :     #[error(transparent)]
    1032              :     GcCutoffs(PageReconstructError),
    1033              : 
    1034              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1035              :     #[error("timeline not found")]
    1036              :     TimelineNotFound,
    1037              : }
    1038              : 
    1039              : impl From<PageReconstructError> for GcError {
    1040            0 :     fn from(value: PageReconstructError) -> Self {
    1041            0 :         match value {
    1042            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1043            0 :             other => Self::GcCutoffs(other),
    1044              :         }
    1045            0 :     }
    1046              : }
    1047              : 
    1048              : impl From<NotInitialized> for GcError {
    1049            0 :     fn from(value: NotInitialized) -> Self {
    1050            0 :         match value {
    1051            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1052            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1053              :         }
    1054            0 :     }
    1055              : }
    1056              : 
    1057              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1058            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1059            0 :         GcError::TimelineCancelled
    1060            0 :     }
    1061              : }
    1062              : 
    1063              : #[derive(thiserror::Error, Debug)]
    1064              : pub(crate) enum LoadConfigError {
    1065              :     #[error("TOML deserialization error: '{0}'")]
    1066              :     DeserializeToml(#[from] toml_edit::de::Error),
    1067              : 
    1068              :     #[error("Config not found at {0}")]
    1069              :     NotFound(Utf8PathBuf),
    1070              : }
    1071              : 
    1072              : impl Tenant {
    1073              :     /// Yet another helper for timeline initialization.
    1074              :     ///
    1075              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1076              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1077              :     /// - Downloads remote index file and adds remote files to the layer map
    1078              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1079              :     ///
    1080              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1081              :     /// it is marked as Active.
    1082              :     #[allow(clippy::too_many_arguments)]
    1083           12 :     async fn timeline_init_and_sync(
    1084           12 :         self: &Arc<Self>,
    1085           12 :         timeline_id: TimelineId,
    1086           12 :         resources: TimelineResources,
    1087           12 :         mut index_part: IndexPart,
    1088           12 :         metadata: TimelineMetadata,
    1089           12 :         previous_heatmap: Option<PreviousHeatmap>,
    1090           12 :         ancestor: Option<Arc<Timeline>>,
    1091           12 :         cause: LoadTimelineCause,
    1092           12 :         ctx: &RequestContext,
    1093           12 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1094           12 :         let tenant_id = self.tenant_shard_id;
    1095           12 : 
    1096           12 :         let import_pgdata = index_part.import_pgdata.take();
    1097           12 :         let idempotency = match &import_pgdata {
    1098            0 :             Some(import_pgdata) => {
    1099            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1100            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1101            0 :                 })
    1102              :             }
    1103              :             None => {
    1104           12 :                 if metadata.ancestor_timeline().is_none() {
    1105            8 :                     CreateTimelineIdempotency::Bootstrap {
    1106            8 :                         pg_version: metadata.pg_version(),
    1107            8 :                     }
    1108              :                 } else {
    1109            4 :                     CreateTimelineIdempotency::Branch {
    1110            4 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1111            4 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1112            4 :                     }
    1113              :                 }
    1114              :             }
    1115              :         };
    1116              : 
    1117           12 :         let timeline = self.create_timeline_struct(
    1118           12 :             timeline_id,
    1119           12 :             &metadata,
    1120           12 :             previous_heatmap,
    1121           12 :             ancestor.clone(),
    1122           12 :             resources,
    1123           12 :             CreateTimelineCause::Load,
    1124           12 :             idempotency.clone(),
    1125           12 :             index_part.gc_compaction.clone(),
    1126           12 :         )?;
    1127           12 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1128           12 :         anyhow::ensure!(
    1129           12 :             disk_consistent_lsn.is_valid(),
    1130            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1131              :         );
    1132           12 :         assert_eq!(
    1133           12 :             disk_consistent_lsn,
    1134           12 :             metadata.disk_consistent_lsn(),
    1135            0 :             "these are used interchangeably"
    1136              :         );
    1137              : 
    1138           12 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1139              : 
    1140           12 :         timeline
    1141           12 :             .load_layer_map(disk_consistent_lsn, index_part)
    1142           12 :             .await
    1143           12 :             .with_context(|| {
    1144            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1145           12 :             })?;
    1146              : 
    1147              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1148              :         // to the archival operation. To allow warming this timeline up, generate
    1149              :         // a previous heatmap which contains all visible layers in the layer map.
    1150              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1151              :         // for the timeline.
    1152           12 :         if matches!(cause, LoadTimelineCause::Unoffload) {
    1153            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1154            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1155            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1156              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1157              :                 // If the current branch point greater than the previous one use the the heatmap
    1158              :                 // we just generated - it should include more layers.
    1159            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1160            0 :                     tline
    1161            0 :                         .previous_heatmap
    1162            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1163            0 :                 } else {
    1164            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1165              :                 }
    1166              : 
    1167            0 :                 match tline.ancestor_timeline() {
    1168            0 :                     Some(ancestor) => {
    1169            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1170              :                             // Ancestor timeline is shutting down.
    1171            0 :                             break;
    1172            0 :                         }
    1173            0 : 
    1174            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1175              :                     }
    1176            0 :                     None => {
    1177            0 :                         tline_ending_at = None;
    1178            0 :                     }
    1179              :                 }
    1180              :             }
    1181           12 :         }
    1182              : 
    1183            0 :         match import_pgdata {
    1184            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1185            0 :                 match cause {
    1186            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1187              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1188            0 :                         unreachable!(
    1189            0 :                             "ImportPgdata should not be reloading timeline import is done and persisted as such in s3"
    1190            0 :                         )
    1191              :                     }
    1192              :                 }
    1193            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1194            0 :                 if !guard.insert(timeline_id) {
    1195              :                     // We should never try and load the same timeline twice during startup
    1196            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1197            0 :                 }
    1198            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1199            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1200            0 :                     owning_tenant: self.clone(),
    1201            0 :                     timeline_id,
    1202            0 :                     idempotency,
    1203            0 :                     // The users of this specific return value don't need the timline_path in there.
    1204            0 :                     timeline_path: timeline
    1205            0 :                         .conf
    1206            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1207            0 :                 };
    1208            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1209            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1210            0 :                         timeline,
    1211            0 :                         import_pgdata,
    1212            0 :                         guard: timeline_create_guard,
    1213            0 :                     },
    1214            0 :                 ))
    1215              :             }
    1216              :             Some(_) | None => {
    1217              :                 {
    1218           12 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1219           12 :                     match timelines_accessor.entry(timeline_id) {
    1220              :                         // We should never try and load the same timeline twice during startup
    1221              :                         Entry::Occupied(_) => {
    1222            0 :                             unreachable!(
    1223            0 :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1224            0 :                             );
    1225              :                         }
    1226           12 :                         Entry::Vacant(v) => {
    1227           12 :                             v.insert(Arc::clone(&timeline));
    1228           12 :                             timeline.maybe_spawn_flush_loop();
    1229           12 :                         }
    1230              :                     }
    1231              :                 }
    1232              : 
    1233              :                 // Sanity check: a timeline should have some content.
    1234           12 :                 anyhow::ensure!(
    1235           12 :                     ancestor.is_some()
    1236            8 :                         || timeline
    1237            8 :                             .layers
    1238            8 :                             .read()
    1239            8 :                             .await
    1240            8 :                             .layer_map()
    1241            8 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1242            8 :                             .iter_historic_layers()
    1243            8 :                             .next()
    1244            8 :                             .is_some(),
    1245            0 :                     "Timeline has no ancestor and no layer files"
    1246              :                 );
    1247              : 
    1248           12 :                 match cause {
    1249           12 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1250              :                     LoadTimelineCause::ImportPgdata {
    1251            0 :                         create_guard,
    1252            0 :                         activate,
    1253            0 :                     } => {
    1254            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1255            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1256            0 :                         match activate {
    1257            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1258            0 :                                 info!("activating timeline after reload from pgdata import task");
    1259            0 :                                 timeline.activate(self.clone(), broker_client, None, ctx);
    1260              :                             }
    1261            0 :                             ActivateTimelineArgs::No => (),
    1262              :                         }
    1263            0 :                         drop(create_guard);
    1264              :                     }
    1265              :                 }
    1266              : 
    1267           12 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1268              :             }
    1269              :         }
    1270           12 :     }
    1271              : 
    1272              :     /// Attach a tenant that's available in cloud storage.
    1273              :     ///
    1274              :     /// This returns quickly, after just creating the in-memory object
    1275              :     /// Tenant struct and launching a background task to download
    1276              :     /// the remote index files.  On return, the tenant is most likely still in
    1277              :     /// Attaching state, and it will become Active once the background task
    1278              :     /// finishes. You can use wait_until_active() to wait for the task to
    1279              :     /// complete.
    1280              :     ///
    1281              :     #[allow(clippy::too_many_arguments)]
    1282            0 :     pub(crate) fn spawn(
    1283            0 :         conf: &'static PageServerConf,
    1284            0 :         tenant_shard_id: TenantShardId,
    1285            0 :         resources: TenantSharedResources,
    1286            0 :         attached_conf: AttachedTenantConf,
    1287            0 :         shard_identity: ShardIdentity,
    1288            0 :         init_order: Option<InitializationOrder>,
    1289            0 :         mode: SpawnMode,
    1290            0 :         ctx: &RequestContext,
    1291            0 :     ) -> Result<Arc<Tenant>, GlobalShutDown> {
    1292            0 :         let wal_redo_manager =
    1293            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1294              : 
    1295              :         let TenantSharedResources {
    1296            0 :             broker_client,
    1297            0 :             remote_storage,
    1298            0 :             deletion_queue_client,
    1299            0 :             l0_flush_global_state,
    1300            0 :         } = resources;
    1301            0 : 
    1302            0 :         let attach_mode = attached_conf.location.attach_mode;
    1303            0 :         let generation = attached_conf.location.generation;
    1304            0 : 
    1305            0 :         let tenant = Arc::new(Tenant::new(
    1306            0 :             TenantState::Attaching,
    1307            0 :             conf,
    1308            0 :             attached_conf,
    1309            0 :             shard_identity,
    1310            0 :             Some(wal_redo_manager),
    1311            0 :             tenant_shard_id,
    1312            0 :             remote_storage.clone(),
    1313            0 :             deletion_queue_client,
    1314            0 :             l0_flush_global_state,
    1315            0 :         ));
    1316            0 : 
    1317            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1318            0 :         // we shut down while attaching.
    1319            0 :         let attach_gate_guard = tenant
    1320            0 :             .gate
    1321            0 :             .enter()
    1322            0 :             .expect("We just created the Tenant: nothing else can have shut it down yet");
    1323            0 : 
    1324            0 :         // Do all the hard work in the background
    1325            0 :         let tenant_clone = Arc::clone(&tenant);
    1326            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1327            0 :         task_mgr::spawn(
    1328            0 :             &tokio::runtime::Handle::current(),
    1329            0 :             TaskKind::Attach,
    1330            0 :             tenant_shard_id,
    1331            0 :             None,
    1332            0 :             "attach tenant",
    1333            0 :             async move {
    1334            0 : 
    1335            0 :                 info!(
    1336              :                     ?attach_mode,
    1337            0 :                     "Attaching tenant"
    1338              :                 );
    1339              : 
    1340            0 :                 let _gate_guard = attach_gate_guard;
    1341            0 : 
    1342            0 :                 // Is this tenant being spawned as part of process startup?
    1343            0 :                 let starting_up = init_order.is_some();
    1344            0 :                 scopeguard::defer! {
    1345            0 :                     if starting_up {
    1346            0 :                         TENANT.startup_complete.inc();
    1347            0 :                     }
    1348            0 :                 }
    1349              : 
    1350              :                 // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
    1351              :                 enum BrokenVerbosity {
    1352              :                     Error,
    1353              :                     Info
    1354              :                 }
    1355            0 :                 let make_broken =
    1356            0 :                     |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
    1357            0 :                         match verbosity {
    1358              :                             BrokenVerbosity::Info => {
    1359            0 :                                 info!("attach cancelled, setting tenant state to Broken: {err}");
    1360              :                             },
    1361              :                             BrokenVerbosity::Error => {
    1362            0 :                                 error!("attach failed, setting tenant state to Broken: {err:?}");
    1363              :                             }
    1364              :                         }
    1365            0 :                         t.state.send_modify(|state| {
    1366            0 :                             // The Stopping case is for when we have passed control on to DeleteTenantFlow:
    1367            0 :                             // if it errors, we will call make_broken when tenant is already in Stopping.
    1368            0 :                             assert!(
    1369            0 :                                 matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
    1370            0 :                                 "the attach task owns the tenant state until activation is complete"
    1371              :                             );
    1372              : 
    1373            0 :                             *state = TenantState::broken_from_reason(err.to_string());
    1374            0 :                         });
    1375            0 :                     };
    1376              : 
    1377              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1378            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1379            0 :                     make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1380            0 :                     return Ok(());
    1381            0 :                 }
    1382            0 : 
    1383            0 :                 let mut init_order = init_order;
    1384            0 :                 // take the completion because initial tenant loading will complete when all of
    1385            0 :                 // these tasks complete.
    1386            0 :                 let _completion = init_order
    1387            0 :                     .as_mut()
    1388            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1389            0 :                 let remote_load_completion = init_order
    1390            0 :                     .as_mut()
    1391            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1392              : 
    1393              :                 enum AttachType<'a> {
    1394              :                     /// We are attaching this tenant lazily in the background.
    1395              :                     Warmup {
    1396              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1397              :                         during_startup: bool
    1398              :                     },
    1399              :                     /// We are attaching this tenant as soon as we can, because for example an
    1400              :                     /// endpoint tried to access it.
    1401              :                     OnDemand,
    1402              :                     /// During normal operations after startup, we are attaching a tenant, and
    1403              :                     /// eager attach was requested.
    1404              :                     Normal,
    1405              :                 }
    1406              : 
    1407            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1408              :                     // Before doing any I/O, wait for at least one of:
    1409              :                     // - A client attempting to access to this tenant (on-demand loading)
    1410              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1411              : 
    1412            0 :                     tokio::select!(
    1413            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1414            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1415            0 :                             tracing::info!("Activating tenant (on-demand)");
    1416            0 :                             AttachType::OnDemand
    1417              :                         },
    1418            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1419            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1420            0 :                             tracing::info!("Activating tenant (warmup)");
    1421            0 :                             AttachType::Warmup {
    1422            0 :                                 _permit,
    1423            0 :                                 during_startup: init_order.is_some()
    1424            0 :                             }
    1425              :                         }
    1426            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1427              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1428              :                             // stayed in Activating for such a long time that shutdown found it in
    1429              :                             // that state.
    1430            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1431              :                             // Make the tenant broken so that set_stopping will not hang waiting for it to leave
    1432              :                             // the Attaching state.  This is an over-reaction (nothing really broke, the tenant is
    1433              :                             // just shutting down), but ensures progress.
    1434            0 :                             make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
    1435            0 :                             return Ok(());
    1436              :                         },
    1437              :                     )
    1438              :                 } else {
    1439              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1440              :                     // concurrent_tenant_warmup queue
    1441            0 :                     AttachType::Normal
    1442              :                 };
    1443              : 
    1444            0 :                 let preload = match &mode {
    1445              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1446            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1447            0 :                         let res = tenant_clone
    1448            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1449            0 :                             .await;
    1450            0 :                         match res {
    1451            0 :                             Ok(p) => Some(p),
    1452            0 :                             Err(e) => {
    1453            0 :                                 make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1454            0 :                                 return Ok(());
    1455              :                             }
    1456              :                         }
    1457              :                     }
    1458              : 
    1459              :                 };
    1460              : 
    1461              :                 // Remote preload is complete.
    1462            0 :                 drop(remote_load_completion);
    1463            0 : 
    1464            0 : 
    1465            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1466            0 :                 let attach_start = std::time::Instant::now();
    1467            0 :                 let attached = {
    1468            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1469            0 :                     tenant_clone.attach(preload, &ctx).await
    1470              :                 };
    1471            0 :                 let attach_duration = attach_start.elapsed();
    1472            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1473            0 : 
    1474            0 :                 match attached {
    1475              :                     Ok(()) => {
    1476            0 :                         info!("attach finished, activating");
    1477            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1478              :                     }
    1479            0 :                     Err(e) => {
    1480            0 :                         make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
    1481            0 :                     }
    1482              :                 }
    1483              : 
    1484              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1485              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1486              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1487              :                 //
    1488              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1489              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1490              :                 // then warmup will wait for that before proceeding to the next tenant.
    1491            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1492            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1493            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1494            0 :                     while futs.next().await.is_some() {}
    1495            0 :                     tracing::info!("Warm-up complete");
    1496            0 :                 }
    1497              : 
    1498            0 :                 Ok(())
    1499            0 :             }
    1500            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1501              :         );
    1502            0 :         Ok(tenant)
    1503            0 :     }
    1504              : 
    1505              :     #[instrument(skip_all)]
    1506              :     pub(crate) async fn preload(
    1507              :         self: &Arc<Self>,
    1508              :         remote_storage: &GenericRemoteStorage,
    1509              :         cancel: CancellationToken,
    1510              :     ) -> anyhow::Result<TenantPreload> {
    1511              :         span::debug_assert_current_span_has_tenant_id();
    1512              :         // Get list of remote timelines
    1513              :         // download index files for every tenant timeline
    1514              :         info!("listing remote timelines");
    1515              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1516              :             remote_storage,
    1517              :             self.tenant_shard_id,
    1518              :             cancel.clone(),
    1519              :         )
    1520              :         .await?;
    1521              :         let (offloaded_add, tenant_manifest) =
    1522              :             match remote_timeline_client::download_tenant_manifest(
    1523              :                 remote_storage,
    1524              :                 &self.tenant_shard_id,
    1525              :                 self.generation,
    1526              :                 &cancel,
    1527              :             )
    1528              :             .await
    1529              :             {
    1530              :                 Ok((tenant_manifest, _generation, _manifest_mtime)) => (
    1531              :                     format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
    1532              :                     tenant_manifest,
    1533              :                 ),
    1534              :                 Err(DownloadError::NotFound) => {
    1535              :                     ("no manifest".to_string(), TenantManifest::empty())
    1536              :                 }
    1537              :                 Err(e) => Err(e)?,
    1538              :             };
    1539              : 
    1540              :         info!(
    1541              :             "found {} timelines, and {offloaded_add}",
    1542              :             remote_timeline_ids.len()
    1543              :         );
    1544              : 
    1545              :         for k in other_keys {
    1546              :             warn!("Unexpected non timeline key {k}");
    1547              :         }
    1548              : 
    1549              :         // Avoid downloading IndexPart of offloaded timelines.
    1550              :         let mut offloaded_with_prefix = HashSet::new();
    1551              :         for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1552              :             if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1553              :                 offloaded_with_prefix.insert(offloaded.timeline_id);
    1554              :             } else {
    1555              :                 // We'll take care later of timelines in the manifest without a prefix
    1556              :             }
    1557              :         }
    1558              : 
    1559              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1560              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1561              :         // will kick the secondary in any case and cause a download.
    1562              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1563              : 
    1564              :         let timelines = self
    1565              :             .load_timelines_metadata(
    1566              :                 remote_timeline_ids,
    1567              :                 remote_storage,
    1568              :                 maybe_heatmap_at,
    1569              :                 cancel,
    1570              :             )
    1571              :             .await?;
    1572              : 
    1573              :         Ok(TenantPreload {
    1574              :             tenant_manifest,
    1575              :             timelines: timelines
    1576              :                 .into_iter()
    1577           12 :                 .map(|(id, tl)| (id, Some(tl)))
    1578            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1579              :                 .collect(),
    1580              :         })
    1581              :     }
    1582              : 
    1583          444 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1584          444 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1585          444 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1586            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1587            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1588            0 :                 Err(err) => {
    1589            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1590            0 :                     None
    1591              :                 }
    1592              :             },
    1593          444 :             Err(err) => match err.kind() {
    1594          444 :                 std::io::ErrorKind::NotFound => None,
    1595              :                 _ => {
    1596            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1597            0 :                     None
    1598              :                 }
    1599              :             },
    1600              :         }
    1601          444 :     }
    1602              : 
    1603              :     ///
    1604              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1605              :     ///
    1606              :     /// No background tasks are started as part of this routine.
    1607              :     ///
    1608          444 :     async fn attach(
    1609          444 :         self: &Arc<Tenant>,
    1610          444 :         preload: Option<TenantPreload>,
    1611          444 :         ctx: &RequestContext,
    1612          444 :     ) -> anyhow::Result<()> {
    1613          444 :         span::debug_assert_current_span_has_tenant_id();
    1614          444 : 
    1615          444 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1616              : 
    1617          444 :         let Some(preload) = preload else {
    1618            0 :             anyhow::bail!(
    1619            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1620            0 :             );
    1621              :         };
    1622              : 
    1623          444 :         let mut offloaded_timeline_ids = HashSet::new();
    1624          444 :         let mut offloaded_timelines_list = Vec::new();
    1625          444 :         for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
    1626            0 :             let timeline_id = timeline_manifest.timeline_id;
    1627            0 :             let offloaded_timeline =
    1628            0 :                 OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1629            0 :             offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1630            0 :             offloaded_timeline_ids.insert(timeline_id);
    1631            0 :         }
    1632              :         // Complete deletions for offloaded timeline id's from manifest.
    1633              :         // The manifest will be uploaded later in this function.
    1634          444 :         offloaded_timelines_list
    1635          444 :             .retain(|(offloaded_id, offloaded)| {
    1636            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1637            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1638            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1639            0 :                 if delete {
    1640            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1641            0 :                     offloaded.defuse_for_tenant_drop();
    1642            0 :                 }
    1643            0 :                 !delete
    1644          444 :         });
    1645          444 : 
    1646          444 :         let mut timelines_to_resume_deletions = vec![];
    1647          444 : 
    1648          444 :         let mut remote_index_and_client = HashMap::new();
    1649          444 :         let mut timeline_ancestors = HashMap::new();
    1650          444 :         let mut existent_timelines = HashSet::new();
    1651          456 :         for (timeline_id, preload) in preload.timelines {
    1652           12 :             let Some(preload) = preload else { continue };
    1653              :             // This is an invariant of the `preload` function's API
    1654           12 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1655           12 :             let index_part = match preload.index_part {
    1656           12 :                 Ok(i) => {
    1657           12 :                     debug!("remote index part exists for timeline {timeline_id}");
    1658              :                     // We found index_part on the remote, this is the standard case.
    1659           12 :                     existent_timelines.insert(timeline_id);
    1660           12 :                     i
    1661              :                 }
    1662              :                 Err(DownloadError::NotFound) => {
    1663              :                     // There is no index_part on the remote. We only get here
    1664              :                     // if there is some prefix for the timeline in the remote storage.
    1665              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1666              :                     // remnant from a prior incomplete creation or deletion attempt.
    1667              :                     // Delete the local directory as the deciding criterion for a
    1668              :                     // timeline's existence is presence of index_part.
    1669            0 :                     info!(%timeline_id, "index_part not found on remote");
    1670            0 :                     continue;
    1671              :                 }
    1672            0 :                 Err(DownloadError::Fatal(why)) => {
    1673            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1674            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1675            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1676            0 :                     anyhow::bail!(why.to_string());
    1677              :                 }
    1678            0 :                 Err(e) => {
    1679            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1680            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1681            0 :                     // as it might be a temporary issue and we don't want to re-download
    1682            0 :                     // everything after it resolves.
    1683            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1684              : 
    1685            0 :                     existent_timelines.insert(timeline_id);
    1686            0 :                     continue;
    1687              :                 }
    1688              :             };
    1689           12 :             match index_part {
    1690           12 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1691           12 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1692           12 :                     remote_index_and_client.insert(
    1693           12 :                         timeline_id,
    1694           12 :                         (index_part, preload.client, preload.previous_heatmap),
    1695           12 :                     );
    1696           12 :                 }
    1697            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1698            0 :                     info!(
    1699            0 :                         "timeline {} is deleted, picking to resume deletion",
    1700              :                         timeline_id
    1701              :                     );
    1702            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1703              :                 }
    1704              :             }
    1705              :         }
    1706              : 
    1707          444 :         let mut gc_blocks = HashMap::new();
    1708              : 
    1709              :         // For every timeline, download the metadata file, scan the local directory,
    1710              :         // and build a layer map that contains an entry for each remote and local
    1711              :         // layer file.
    1712          444 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1713          456 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1714           12 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1715           12 :                 .remove(&timeline_id)
    1716           12 :                 .expect("just put it in above");
    1717              : 
    1718           12 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1719              :                 // could just filter these away, but it helps while testing
    1720            0 :                 anyhow::ensure!(
    1721            0 :                     !blocking.reasons.is_empty(),
    1722            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1723              :                 );
    1724            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1725            0 :                 assert!(prev.is_none());
    1726           12 :             }
    1727              : 
    1728              :             // TODO again handle early failure
    1729           12 :             let effect = self
    1730           12 :                 .load_remote_timeline(
    1731           12 :                     timeline_id,
    1732           12 :                     index_part,
    1733           12 :                     remote_metadata,
    1734           12 :                     previous_heatmap,
    1735           12 :                     self.get_timeline_resources_for(remote_client),
    1736           12 :                     LoadTimelineCause::Attach,
    1737           12 :                     ctx,
    1738           12 :                 )
    1739           12 :                 .await
    1740           12 :                 .with_context(|| {
    1741            0 :                     format!(
    1742            0 :                         "failed to load remote timeline {} for tenant {}",
    1743            0 :                         timeline_id, self.tenant_shard_id
    1744            0 :                     )
    1745           12 :                 })?;
    1746              : 
    1747           12 :             match effect {
    1748           12 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1749           12 :                     // activation happens later, on Tenant::activate
    1750           12 :                 }
    1751              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1752              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1753            0 :                         timeline,
    1754            0 :                         import_pgdata,
    1755            0 :                         guard,
    1756            0 :                     },
    1757            0 :                 ) => {
    1758            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1759            0 :                         timeline,
    1760            0 :                         import_pgdata,
    1761            0 :                         ActivateTimelineArgs::No,
    1762            0 :                         guard,
    1763            0 :                     ));
    1764            0 :                 }
    1765              :             }
    1766              :         }
    1767              : 
    1768              :         // Walk through deleted timelines, resume deletion
    1769          444 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1770            0 :             remote_timeline_client
    1771            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1772            0 :                 .context("init queue stopped")
    1773            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1774              : 
    1775            0 :             DeleteTimelineFlow::resume_deletion(
    1776            0 :                 Arc::clone(self),
    1777            0 :                 timeline_id,
    1778            0 :                 &index_part.metadata,
    1779            0 :                 remote_timeline_client,
    1780            0 :             )
    1781            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1782            0 :             .await
    1783            0 :             .context("resume_deletion")
    1784            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1785              :         }
    1786          444 :         let needs_manifest_upload =
    1787          444 :             offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
    1788          444 :         {
    1789          444 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1790          444 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1791          444 :         }
    1792          444 :         if needs_manifest_upload {
    1793            0 :             self.store_tenant_manifest().await?;
    1794          444 :         }
    1795              : 
    1796              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1797              :         // IndexPart is the source of truth.
    1798          444 :         self.clean_up_timelines(&existent_timelines)?;
    1799              : 
    1800          444 :         self.gc_block.set_scanned(gc_blocks);
    1801          444 : 
    1802          444 :         fail::fail_point!("attach-before-activate", |_| {
    1803            0 :             anyhow::bail!("attach-before-activate");
    1804          444 :         });
    1805          444 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1806              : 
    1807          444 :         info!("Done");
    1808              : 
    1809          444 :         Ok(())
    1810          444 :     }
    1811              : 
    1812              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1813              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1814              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1815          444 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1816          444 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1817              : 
    1818          444 :         let entries = match timelines_dir.read_dir_utf8() {
    1819          444 :             Ok(d) => d,
    1820            0 :             Err(e) => {
    1821            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1822            0 :                     return Ok(());
    1823              :                 } else {
    1824            0 :                     return Err(e).context("list timelines directory for tenant");
    1825              :                 }
    1826              :             }
    1827              :         };
    1828              : 
    1829          460 :         for entry in entries {
    1830           16 :             let entry = entry.context("read timeline dir entry")?;
    1831           16 :             let entry_path = entry.path();
    1832              : 
    1833           16 :             let purge = if crate::is_temporary(entry_path) {
    1834            0 :                 true
    1835              :             } else {
    1836           16 :                 match TimelineId::try_from(entry_path.file_name()) {
    1837           16 :                     Ok(i) => {
    1838           16 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1839           16 :                         !existent_timelines.contains(&i)
    1840              :                     }
    1841            0 :                     Err(e) => {
    1842            0 :                         tracing::warn!(
    1843            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1844              :                         );
    1845              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1846            0 :                         false
    1847              :                     }
    1848              :                 }
    1849              :             };
    1850              : 
    1851           16 :             if purge {
    1852            4 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1853            4 :                 if let Err(e) = match entry.file_type() {
    1854            4 :                     Ok(t) => if t.is_dir() {
    1855            4 :                         std::fs::remove_dir_all(entry_path)
    1856              :                     } else {
    1857            0 :                         std::fs::remove_file(entry_path)
    1858              :                     }
    1859            4 :                     .or_else(fs_ext::ignore_not_found),
    1860            0 :                     Err(e) => Err(e),
    1861              :                 } {
    1862            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1863            4 :                 }
    1864           12 :             }
    1865              :         }
    1866              : 
    1867          444 :         Ok(())
    1868          444 :     }
    1869              : 
    1870              :     /// Get sum of all remote timelines sizes
    1871              :     ///
    1872              :     /// This function relies on the index_part instead of listing the remote storage
    1873            0 :     pub fn remote_size(&self) -> u64 {
    1874            0 :         let mut size = 0;
    1875              : 
    1876            0 :         for timeline in self.list_timelines() {
    1877            0 :             size += timeline.remote_client.get_remote_physical_size();
    1878            0 :         }
    1879              : 
    1880            0 :         size
    1881            0 :     }
    1882              : 
    1883              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1884              :     #[allow(clippy::too_many_arguments)]
    1885              :     async fn load_remote_timeline(
    1886              :         self: &Arc<Self>,
    1887              :         timeline_id: TimelineId,
    1888              :         index_part: IndexPart,
    1889              :         remote_metadata: TimelineMetadata,
    1890              :         previous_heatmap: Option<PreviousHeatmap>,
    1891              :         resources: TimelineResources,
    1892              :         cause: LoadTimelineCause,
    1893              :         ctx: &RequestContext,
    1894              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1895              :         span::debug_assert_current_span_has_tenant_id();
    1896              : 
    1897              :         info!("downloading index file for timeline {}", timeline_id);
    1898              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1899              :             .await
    1900              :             .context("Failed to create new timeline directory")?;
    1901              : 
    1902              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1903              :             let timelines = self.timelines.lock().unwrap();
    1904              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1905            0 :                 || {
    1906            0 :                     anyhow::anyhow!(
    1907            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1908            0 :                     )
    1909            0 :                 },
    1910              :             )?))
    1911              :         } else {
    1912              :             None
    1913              :         };
    1914              : 
    1915              :         self.timeline_init_and_sync(
    1916              :             timeline_id,
    1917              :             resources,
    1918              :             index_part,
    1919              :             remote_metadata,
    1920              :             previous_heatmap,
    1921              :             ancestor,
    1922              :             cause,
    1923              :             ctx,
    1924              :         )
    1925              :         .await
    1926              :     }
    1927              : 
    1928          444 :     async fn load_timelines_metadata(
    1929          444 :         self: &Arc<Tenant>,
    1930          444 :         timeline_ids: HashSet<TimelineId>,
    1931          444 :         remote_storage: &GenericRemoteStorage,
    1932          444 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    1933          444 :         cancel: CancellationToken,
    1934          444 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1935          444 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    1936          444 : 
    1937          444 :         let mut part_downloads = JoinSet::new();
    1938          456 :         for timeline_id in timeline_ids {
    1939           12 :             let cancel_clone = cancel.clone();
    1940           12 : 
    1941           12 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    1942            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    1943            0 :                     heatmap: h,
    1944            0 :                     read_at: hs.1,
    1945            0 :                     end_lsn: None,
    1946            0 :                 })
    1947           12 :             });
    1948           12 :             part_downloads.spawn(
    1949           12 :                 self.load_timeline_metadata(
    1950           12 :                     timeline_id,
    1951           12 :                     remote_storage.clone(),
    1952           12 :                     previous_timeline_heatmap,
    1953           12 :                     cancel_clone,
    1954           12 :                 )
    1955           12 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    1956              :             );
    1957              :         }
    1958              : 
    1959          444 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1960              : 
    1961              :         loop {
    1962          456 :             tokio::select!(
    1963          456 :                 next = part_downloads.join_next() => {
    1964          456 :                     match next {
    1965           12 :                         Some(result) => {
    1966           12 :                             let preload = result.context("join preload task")?;
    1967           12 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1968              :                         },
    1969              :                         None => {
    1970          444 :                             break;
    1971              :                         }
    1972              :                     }
    1973              :                 },
    1974          456 :                 _ = cancel.cancelled() => {
    1975            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    1976              :                 }
    1977              :             )
    1978              :         }
    1979              : 
    1980          444 :         Ok(timeline_preloads)
    1981          444 :     }
    1982              : 
    1983           12 :     fn build_timeline_client(
    1984           12 :         &self,
    1985           12 :         timeline_id: TimelineId,
    1986           12 :         remote_storage: GenericRemoteStorage,
    1987           12 :     ) -> RemoteTimelineClient {
    1988           12 :         RemoteTimelineClient::new(
    1989           12 :             remote_storage.clone(),
    1990           12 :             self.deletion_queue_client.clone(),
    1991           12 :             self.conf,
    1992           12 :             self.tenant_shard_id,
    1993           12 :             timeline_id,
    1994           12 :             self.generation,
    1995           12 :             &self.tenant_conf.load().location,
    1996           12 :         )
    1997           12 :     }
    1998              : 
    1999           12 :     fn load_timeline_metadata(
    2000           12 :         self: &Arc<Tenant>,
    2001           12 :         timeline_id: TimelineId,
    2002           12 :         remote_storage: GenericRemoteStorage,
    2003           12 :         previous_heatmap: Option<PreviousHeatmap>,
    2004           12 :         cancel: CancellationToken,
    2005           12 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2006           12 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2007           12 :         async move {
    2008           12 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2009           12 :             debug!("starting index part download");
    2010              : 
    2011           12 :             let index_part = client.download_index_file(&cancel).await;
    2012              : 
    2013           12 :             debug!("finished index part download");
    2014              : 
    2015           12 :             TimelinePreload {
    2016           12 :                 client,
    2017           12 :                 timeline_id,
    2018           12 :                 index_part,
    2019           12 :                 previous_heatmap,
    2020           12 :             }
    2021           12 :         }
    2022           12 :     }
    2023              : 
    2024            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2025            0 :         timeline_id: TimelineId,
    2026            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2027            0 :     ) -> Result<(), TimelineArchivalError> {
    2028            0 :         let children: Vec<TimelineId> = timelines
    2029            0 :             .iter()
    2030            0 :             .filter_map(|(id, entry)| {
    2031            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2032            0 :                     return None;
    2033            0 :                 }
    2034            0 :                 if entry.is_archived() == Some(true) {
    2035            0 :                     return None;
    2036            0 :                 }
    2037            0 :                 Some(*id)
    2038            0 :             })
    2039            0 :             .collect();
    2040            0 : 
    2041            0 :         if !children.is_empty() {
    2042            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2043            0 :         }
    2044            0 :         Ok(())
    2045            0 :     }
    2046              : 
    2047            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2048            0 :         ancestor_timeline_id: TimelineId,
    2049            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2050            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2051            0 :             '_,
    2052            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2053            0 :         >,
    2054            0 :     ) -> Result<(), TimelineArchivalError> {
    2055            0 :         let has_archived_parent =
    2056            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2057            0 :                 ancestor_timeline.is_archived() == Some(true)
    2058            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2059            0 :                 true
    2060              :             } else {
    2061            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2062            0 :                 if cfg!(debug_assertions) {
    2063            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2064            0 :                 }
    2065            0 :                 return Err(TimelineArchivalError::NotFound);
    2066              :             };
    2067            0 :         if has_archived_parent {
    2068            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2069            0 :                 ancestor_timeline_id,
    2070            0 :             ));
    2071            0 :         }
    2072            0 :         Ok(())
    2073            0 :     }
    2074              : 
    2075            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2076            0 :         timeline: &Arc<Timeline>,
    2077            0 :     ) -> Result<(), TimelineArchivalError> {
    2078            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2079            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2080            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2081            0 :                     ancestor_timeline.timeline_id,
    2082            0 :                 ));
    2083            0 :             }
    2084            0 :         }
    2085            0 :         Ok(())
    2086            0 :     }
    2087              : 
    2088              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2089              :     ///
    2090              :     /// Counterpart to [`offload_timeline`].
    2091            0 :     async fn unoffload_timeline(
    2092            0 :         self: &Arc<Self>,
    2093            0 :         timeline_id: TimelineId,
    2094            0 :         broker_client: storage_broker::BrokerClientChannel,
    2095            0 :         ctx: RequestContext,
    2096            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2097            0 :         info!("unoffloading timeline");
    2098              : 
    2099              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2100              :         // We expect callers of this function to ensure this.
    2101            0 :         match self.current_state() {
    2102              :             TenantState::Activating { .. }
    2103              :             | TenantState::Attaching
    2104              :             | TenantState::Broken { .. } => {
    2105            0 :                 panic!("Timeline expected to be active")
    2106              :             }
    2107            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2108            0 :             TenantState::Active => {}
    2109            0 :         }
    2110            0 :         let cancel = self.cancel.clone();
    2111            0 : 
    2112            0 :         // Protect against concurrent attempts to use this TimelineId
    2113            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2114            0 :         let allow_offloaded = true;
    2115            0 :         let _create_guard = self
    2116            0 :             .create_timeline_create_guard(
    2117            0 :                 timeline_id,
    2118            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2119            0 :                 allow_offloaded,
    2120            0 :             )
    2121            0 :             .map_err(|err| match err {
    2122            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2123              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2124            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2125              :                 }
    2126            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2127            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2128            0 :             })?;
    2129              : 
    2130            0 :         let timeline_preload = self
    2131            0 :             .load_timeline_metadata(
    2132            0 :                 timeline_id,
    2133            0 :                 self.remote_storage.clone(),
    2134            0 :                 None,
    2135            0 :                 cancel.clone(),
    2136            0 :             )
    2137            0 :             .await;
    2138              : 
    2139            0 :         let index_part = match timeline_preload.index_part {
    2140            0 :             Ok(index_part) => {
    2141            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2142            0 :                 index_part
    2143              :             }
    2144              :             Err(DownloadError::NotFound) => {
    2145            0 :                 error!(%timeline_id, "index_part not found on remote");
    2146            0 :                 return Err(TimelineArchivalError::NotFound);
    2147              :             }
    2148            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2149            0 :             Err(e) => {
    2150            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2151            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2152            0 :                 return Err(TimelineArchivalError::Other(
    2153            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2154            0 :                 ));
    2155              :             }
    2156              :         };
    2157            0 :         let index_part = match index_part {
    2158            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2159            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2160            0 :                 info!("timeline is deleted according to index_part.json");
    2161            0 :                 return Err(TimelineArchivalError::NotFound);
    2162              :             }
    2163              :         };
    2164            0 :         let remote_metadata = index_part.metadata.clone();
    2165            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2166            0 :         self.load_remote_timeline(
    2167            0 :             timeline_id,
    2168            0 :             index_part,
    2169            0 :             remote_metadata,
    2170            0 :             None,
    2171            0 :             timeline_resources,
    2172            0 :             LoadTimelineCause::Unoffload,
    2173            0 :             &ctx,
    2174            0 :         )
    2175            0 :         .await
    2176            0 :         .with_context(|| {
    2177            0 :             format!(
    2178            0 :                 "failed to load remote timeline {} for tenant {}",
    2179            0 :                 timeline_id, self.tenant_shard_id
    2180            0 :             )
    2181            0 :         })
    2182            0 :         .map_err(TimelineArchivalError::Other)?;
    2183              : 
    2184            0 :         let timeline = {
    2185            0 :             let timelines = self.timelines.lock().unwrap();
    2186            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2187            0 :                 warn!("timeline not available directly after attach");
    2188              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2189              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2190            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2191            0 :                     "timeline not available directly after attach"
    2192            0 :                 )));
    2193              :             };
    2194            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2195            0 :             match offloaded_timelines.remove(&timeline_id) {
    2196            0 :                 Some(offloaded) => {
    2197            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2198            0 :                 }
    2199            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2200              :             }
    2201              : 
    2202            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2203            0 : 
    2204            0 :             Arc::clone(timeline)
    2205            0 :         };
    2206            0 : 
    2207            0 :         // Upload new list of offloaded timelines to S3
    2208            0 :         self.store_tenant_manifest().await?;
    2209              : 
    2210              :         // Activate the timeline (if it makes sense)
    2211            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2212            0 :             let background_jobs_can_start = None;
    2213            0 :             timeline.activate(
    2214            0 :                 self.clone(),
    2215            0 :                 broker_client.clone(),
    2216            0 :                 background_jobs_can_start,
    2217            0 :                 &ctx,
    2218            0 :             );
    2219            0 :         }
    2220              : 
    2221            0 :         info!("timeline unoffloading complete");
    2222            0 :         Ok(timeline)
    2223            0 :     }
    2224              : 
    2225            0 :     pub(crate) async fn apply_timeline_archival_config(
    2226            0 :         self: &Arc<Self>,
    2227            0 :         timeline_id: TimelineId,
    2228            0 :         new_state: TimelineArchivalState,
    2229            0 :         broker_client: storage_broker::BrokerClientChannel,
    2230            0 :         ctx: RequestContext,
    2231            0 :     ) -> Result<(), TimelineArchivalError> {
    2232            0 :         info!("setting timeline archival config");
    2233              :         // First part: figure out what is needed to do, and do validation
    2234            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2235            0 :             let timelines = self.timelines.lock().unwrap();
    2236              : 
    2237            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2238            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2239            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2240            0 :                     return Err(TimelineArchivalError::NotFound);
    2241              :                 };
    2242            0 :                 if new_state == TimelineArchivalState::Archived {
    2243              :                     // It's offloaded already, so nothing to do
    2244            0 :                     return Ok(());
    2245            0 :                 }
    2246            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2247            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2248            0 :                         ancestor_timeline_id,
    2249            0 :                         &timelines,
    2250            0 :                         &offloaded_timelines,
    2251            0 :                     )?;
    2252            0 :                 }
    2253            0 :                 break 'outer None;
    2254              :             };
    2255              : 
    2256              :             // Do some validation. We release the timelines lock below, so there is potential
    2257              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2258              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2259            0 :             match new_state {
    2260              :                 TimelineArchivalState::Unarchived => {
    2261            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2262              :                 }
    2263              :                 TimelineArchivalState::Archived => {
    2264            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2265              :                 }
    2266              :             }
    2267            0 :             Some(Arc::clone(timeline))
    2268              :         };
    2269              : 
    2270              :         // Second part: unoffload timeline (if needed)
    2271            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2272            0 :             timeline
    2273              :         } else {
    2274              :             // Turn offloaded timeline into a non-offloaded one
    2275            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2276            0 :                 .await?
    2277              :         };
    2278              : 
    2279              :         // Third part: upload new timeline archival state and block until it is present in S3
    2280            0 :         let upload_needed = match timeline
    2281            0 :             .remote_client
    2282            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2283              :         {
    2284            0 :             Ok(upload_needed) => upload_needed,
    2285            0 :             Err(e) => {
    2286            0 :                 if timeline.cancel.is_cancelled() {
    2287            0 :                     return Err(TimelineArchivalError::Cancelled);
    2288              :                 } else {
    2289            0 :                     return Err(TimelineArchivalError::Other(e));
    2290              :                 }
    2291              :             }
    2292              :         };
    2293              : 
    2294            0 :         if upload_needed {
    2295            0 :             info!("Uploading new state");
    2296              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2297            0 :             let Ok(v) =
    2298            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2299              :             else {
    2300            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2301            0 :                 return Err(TimelineArchivalError::Timeout);
    2302              :             };
    2303            0 :             v.map_err(|e| match e {
    2304            0 :                 WaitCompletionError::NotInitialized(e) => {
    2305            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2306              :                 }
    2307              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2308            0 :                     TimelineArchivalError::Cancelled
    2309              :                 }
    2310            0 :             })?;
    2311            0 :         }
    2312            0 :         Ok(())
    2313            0 :     }
    2314              : 
    2315            4 :     pub fn get_offloaded_timeline(
    2316            4 :         &self,
    2317            4 :         timeline_id: TimelineId,
    2318            4 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2319            4 :         self.timelines_offloaded
    2320            4 :             .lock()
    2321            4 :             .unwrap()
    2322            4 :             .get(&timeline_id)
    2323            4 :             .map(Arc::clone)
    2324            4 :             .ok_or(GetTimelineError::NotFound {
    2325            4 :                 tenant_id: self.tenant_shard_id,
    2326            4 :                 timeline_id,
    2327            4 :             })
    2328            4 :     }
    2329              : 
    2330            8 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2331            8 :         self.tenant_shard_id
    2332            8 :     }
    2333              : 
    2334              :     /// Get Timeline handle for given Neon timeline ID.
    2335              :     /// This function is idempotent. It doesn't change internal state in any way.
    2336          444 :     pub fn get_timeline(
    2337          444 :         &self,
    2338          444 :         timeline_id: TimelineId,
    2339          444 :         active_only: bool,
    2340          444 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2341          444 :         let timelines_accessor = self.timelines.lock().unwrap();
    2342          444 :         let timeline = timelines_accessor
    2343          444 :             .get(&timeline_id)
    2344          444 :             .ok_or(GetTimelineError::NotFound {
    2345          444 :                 tenant_id: self.tenant_shard_id,
    2346          444 :                 timeline_id,
    2347          444 :             })?;
    2348              : 
    2349          440 :         if active_only && !timeline.is_active() {
    2350            0 :             Err(GetTimelineError::NotActive {
    2351            0 :                 tenant_id: self.tenant_shard_id,
    2352            0 :                 timeline_id,
    2353            0 :                 state: timeline.current_state(),
    2354            0 :             })
    2355              :         } else {
    2356          440 :             Ok(Arc::clone(timeline))
    2357              :         }
    2358          444 :     }
    2359              : 
    2360              :     /// Lists timelines the tenant contains.
    2361              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2362            0 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2363            0 :         self.timelines
    2364            0 :             .lock()
    2365            0 :             .unwrap()
    2366            0 :             .values()
    2367            0 :             .map(Arc::clone)
    2368            0 :             .collect()
    2369            0 :     }
    2370              : 
    2371              :     /// Lists timelines the tenant manages, including offloaded ones.
    2372              :     ///
    2373              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2374            0 :     pub fn list_timelines_and_offloaded(
    2375            0 :         &self,
    2376            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2377            0 :         let timelines = self
    2378            0 :             .timelines
    2379            0 :             .lock()
    2380            0 :             .unwrap()
    2381            0 :             .values()
    2382            0 :             .map(Arc::clone)
    2383            0 :             .collect();
    2384            0 :         let offloaded = self
    2385            0 :             .timelines_offloaded
    2386            0 :             .lock()
    2387            0 :             .unwrap()
    2388            0 :             .values()
    2389            0 :             .map(Arc::clone)
    2390            0 :             .collect();
    2391            0 :         (timelines, offloaded)
    2392            0 :     }
    2393              : 
    2394            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2395            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2396            0 :     }
    2397              : 
    2398              :     /// This is used by tests & import-from-basebackup.
    2399              :     ///
    2400              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2401              :     /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2402              :     ///
    2403              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2404              :     /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
    2405              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2406              :     /// to the [`Tenant::timelines`].
    2407              :     ///
    2408              :     /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
    2409          428 :     pub(crate) async fn create_empty_timeline(
    2410          428 :         self: &Arc<Self>,
    2411          428 :         new_timeline_id: TimelineId,
    2412          428 :         initdb_lsn: Lsn,
    2413          428 :         pg_version: u32,
    2414          428 :         _ctx: &RequestContext,
    2415          428 :     ) -> anyhow::Result<UninitializedTimeline> {
    2416          428 :         anyhow::ensure!(
    2417          428 :             self.is_active(),
    2418            0 :             "Cannot create empty timelines on inactive tenant"
    2419              :         );
    2420              : 
    2421              :         // Protect against concurrent attempts to use this TimelineId
    2422          428 :         let create_guard = match self
    2423          428 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2424          428 :             .await?
    2425              :         {
    2426          424 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2427              :             StartCreatingTimelineResult::Idempotent(_) => {
    2428            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2429              :             }
    2430              :         };
    2431              : 
    2432          424 :         let new_metadata = TimelineMetadata::new(
    2433          424 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2434          424 :             // make it valid, before calling finish_creation()
    2435          424 :             Lsn(0),
    2436          424 :             None,
    2437          424 :             None,
    2438          424 :             Lsn(0),
    2439          424 :             initdb_lsn,
    2440          424 :             initdb_lsn,
    2441          424 :             pg_version,
    2442          424 :         );
    2443          424 :         self.prepare_new_timeline(
    2444          424 :             new_timeline_id,
    2445          424 :             &new_metadata,
    2446          424 :             create_guard,
    2447          424 :             initdb_lsn,
    2448          424 :             None,
    2449          424 :         )
    2450          424 :         .await
    2451          428 :     }
    2452              : 
    2453              :     /// Helper for unit tests to create an empty timeline.
    2454              :     ///
    2455              :     /// The timeline is has state value `Active` but its background loops are not running.
    2456              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2457              :     // Our current tests don't need the background loops.
    2458              :     #[cfg(test)]
    2459          408 :     pub async fn create_test_timeline(
    2460          408 :         self: &Arc<Self>,
    2461          408 :         new_timeline_id: TimelineId,
    2462          408 :         initdb_lsn: Lsn,
    2463          408 :         pg_version: u32,
    2464          408 :         ctx: &RequestContext,
    2465          408 :     ) -> anyhow::Result<Arc<Timeline>> {
    2466          408 :         let uninit_tl = self
    2467          408 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2468          408 :             .await?;
    2469          408 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2470          408 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2471              : 
    2472              :         // Setup minimum keys required for the timeline to be usable.
    2473          408 :         let mut modification = tline.begin_modification(initdb_lsn);
    2474          408 :         modification
    2475          408 :             .init_empty_test_timeline()
    2476          408 :             .context("init_empty_test_timeline")?;
    2477          408 :         modification
    2478          408 :             .commit(ctx)
    2479          408 :             .await
    2480          408 :             .context("commit init_empty_test_timeline modification")?;
    2481              : 
    2482              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2483          408 :         tline.maybe_spawn_flush_loop();
    2484          408 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2485              : 
    2486              :         // Make sure the freeze_and_flush reaches remote storage.
    2487          408 :         tline.remote_client.wait_completion().await.unwrap();
    2488              : 
    2489          408 :         let tl = uninit_tl.finish_creation().await?;
    2490              :         // The non-test code would call tl.activate() here.
    2491          408 :         tl.set_state(TimelineState::Active);
    2492          408 :         Ok(tl)
    2493          408 :     }
    2494              : 
    2495              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2496              :     #[cfg(test)]
    2497              :     #[allow(clippy::too_many_arguments)]
    2498           80 :     pub async fn create_test_timeline_with_layers(
    2499           80 :         self: &Arc<Self>,
    2500           80 :         new_timeline_id: TimelineId,
    2501           80 :         initdb_lsn: Lsn,
    2502           80 :         pg_version: u32,
    2503           80 :         ctx: &RequestContext,
    2504           80 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2505           80 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2506           80 :         end_lsn: Lsn,
    2507           80 :     ) -> anyhow::Result<Arc<Timeline>> {
    2508              :         use checks::check_valid_layermap;
    2509              :         use itertools::Itertools;
    2510              : 
    2511           80 :         let tline = self
    2512           80 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2513           80 :             .await?;
    2514           80 :         tline.force_advance_lsn(end_lsn);
    2515          252 :         for deltas in delta_layer_desc {
    2516          172 :             tline
    2517          172 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2518          172 :                 .await?;
    2519              :         }
    2520          192 :         for (lsn, images) in image_layer_desc {
    2521          112 :             tline
    2522          112 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2523          112 :                 .await?;
    2524              :         }
    2525           80 :         let layer_names = tline
    2526           80 :             .layers
    2527           80 :             .read()
    2528           80 :             .await
    2529           80 :             .layer_map()
    2530           80 :             .unwrap()
    2531           80 :             .iter_historic_layers()
    2532          364 :             .map(|layer| layer.layer_name())
    2533           80 :             .collect_vec();
    2534           80 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2535            0 :             bail!("invalid layermap: {err}");
    2536           80 :         }
    2537           80 :         Ok(tline)
    2538           80 :     }
    2539              : 
    2540              :     /// Create a new timeline.
    2541              :     ///
    2542              :     /// Returns the new timeline ID and reference to its Timeline object.
    2543              :     ///
    2544              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2545              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2546              :     #[allow(clippy::too_many_arguments)]
    2547            0 :     pub(crate) async fn create_timeline(
    2548            0 :         self: &Arc<Tenant>,
    2549            0 :         params: CreateTimelineParams,
    2550            0 :         broker_client: storage_broker::BrokerClientChannel,
    2551            0 :         ctx: &RequestContext,
    2552            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2553            0 :         if !self.is_active() {
    2554            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2555            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2556              :             } else {
    2557            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2558            0 :                     "Cannot create timelines on inactive tenant"
    2559            0 :                 )));
    2560              :             }
    2561            0 :         }
    2562              : 
    2563            0 :         let _gate = self
    2564            0 :             .gate
    2565            0 :             .enter()
    2566            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2567              : 
    2568            0 :         let result: CreateTimelineResult = match params {
    2569              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2570            0 :                 new_timeline_id,
    2571            0 :                 existing_initdb_timeline_id,
    2572            0 :                 pg_version,
    2573            0 :             }) => {
    2574            0 :                 self.bootstrap_timeline(
    2575            0 :                     new_timeline_id,
    2576            0 :                     pg_version,
    2577            0 :                     existing_initdb_timeline_id,
    2578            0 :                     ctx,
    2579            0 :                 )
    2580            0 :                 .await?
    2581              :             }
    2582              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2583            0 :                 new_timeline_id,
    2584            0 :                 ancestor_timeline_id,
    2585            0 :                 mut ancestor_start_lsn,
    2586              :             }) => {
    2587            0 :                 let ancestor_timeline = self
    2588            0 :                     .get_timeline(ancestor_timeline_id, false)
    2589            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2590              : 
    2591              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2592              :                 // ready for other purposes either.
    2593            0 :                 if !ancestor_timeline.is_active() {
    2594            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2595            0 :                 }
    2596            0 : 
    2597            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2598            0 :                     info!("tried to branch archived timeline");
    2599            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2600            0 :                 }
    2601              : 
    2602            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2603            0 :                     *lsn = lsn.align();
    2604            0 : 
    2605            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2606            0 :                     if ancestor_ancestor_lsn > *lsn {
    2607              :                         // can we safely just branch from the ancestor instead?
    2608            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2609            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2610            0 :                             lsn,
    2611            0 :                             ancestor_timeline_id,
    2612            0 :                             ancestor_ancestor_lsn,
    2613            0 :                         )));
    2614            0 :                     }
    2615            0 : 
    2616            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2617            0 :                     // to the requested branch point. The repository code itself doesn't
    2618            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2619            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2620            0 :                     // sizes etc. and that would get confused if the previous page versions
    2621            0 :                     // are not in the repository yet.
    2622            0 :                     ancestor_timeline
    2623            0 :                         .wait_lsn(
    2624            0 :                             *lsn,
    2625            0 :                             timeline::WaitLsnWaiter::Tenant,
    2626            0 :                             timeline::WaitLsnTimeout::Default,
    2627            0 :                             ctx,
    2628            0 :                         )
    2629            0 :                         .await
    2630            0 :                         .map_err(|e| match e {
    2631            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2632            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2633              :                             }
    2634            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2635            0 :                         })?;
    2636            0 :                 }
    2637              : 
    2638            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2639            0 :                     .await?
    2640              :             }
    2641            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2642            0 :                 self.create_timeline_import_pgdata(
    2643            0 :                     params,
    2644            0 :                     ActivateTimelineArgs::Yes {
    2645            0 :                         broker_client: broker_client.clone(),
    2646            0 :                     },
    2647            0 :                     ctx,
    2648            0 :                 )
    2649            0 :                 .await?
    2650              :             }
    2651              :         };
    2652              : 
    2653              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2654              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2655              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2656              :         //
    2657              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2658              :         // assume that, because they can see the timeline via API, that the creation is done and
    2659              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2660              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2661              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2662              :         //
    2663              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2664              :         // creation API until it returns success. Only then is durability guaranteed.
    2665            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2666            0 :         result
    2667            0 :             .timeline()
    2668            0 :             .remote_client
    2669            0 :             .wait_completion()
    2670            0 :             .await
    2671            0 :             .map_err(|e| match e {
    2672              :                 WaitCompletionError::NotInitialized(
    2673            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2674            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2675              :                 WaitCompletionError::NotInitialized(_) => {
    2676              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2677            0 :                     debug_assert!(false);
    2678            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2679              :                 }
    2680              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2681            0 :                     CreateTimelineError::ShuttingDown
    2682              :                 }
    2683            0 :             })?;
    2684              : 
    2685              :         // The creating task is responsible for activating the timeline.
    2686              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2687              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2688            0 :         let activated_timeline = match result {
    2689            0 :             CreateTimelineResult::Created(timeline) => {
    2690            0 :                 timeline.activate(self.clone(), broker_client, None, ctx);
    2691            0 :                 timeline
    2692              :             }
    2693            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2694            0 :                 info!(
    2695            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2696              :                 );
    2697            0 :                 timeline
    2698              :             }
    2699            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2700            0 :                 info!(
    2701            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2702              :                 );
    2703            0 :                 timeline
    2704              :             }
    2705              :         };
    2706              : 
    2707            0 :         Ok(activated_timeline)
    2708            0 :     }
    2709              : 
    2710              :     /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
    2711              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2712              :     /// [`Tenant::timelines`] map when the import completes.
    2713              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2714              :     /// for the response.
    2715            0 :     async fn create_timeline_import_pgdata(
    2716            0 :         self: &Arc<Tenant>,
    2717            0 :         params: CreateTimelineParamsImportPgdata,
    2718            0 :         activate: ActivateTimelineArgs,
    2719            0 :         ctx: &RequestContext,
    2720            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2721            0 :         let CreateTimelineParamsImportPgdata {
    2722            0 :             new_timeline_id,
    2723            0 :             location,
    2724            0 :             idempotency_key,
    2725            0 :         } = params;
    2726            0 : 
    2727            0 :         let started_at = chrono::Utc::now().naive_utc();
    2728              : 
    2729              :         //
    2730              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2731              :         // is the canonical way we do it.
    2732              :         // - create an empty timeline in-memory
    2733              :         // - use its remote_timeline_client to do the upload
    2734              :         // - dispose of the uninit timeline
    2735              :         // - keep the creation guard alive
    2736              : 
    2737            0 :         let timeline_create_guard = match self
    2738            0 :             .start_creating_timeline(
    2739            0 :                 new_timeline_id,
    2740            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2741            0 :                     idempotency_key: idempotency_key.clone(),
    2742            0 :                 }),
    2743            0 :             )
    2744            0 :             .await?
    2745              :         {
    2746            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2747            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2748            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2749              :             }
    2750              :         };
    2751              : 
    2752            0 :         let mut uninit_timeline = {
    2753            0 :             let this = &self;
    2754            0 :             let initdb_lsn = Lsn(0);
    2755            0 :             let _ctx = ctx;
    2756            0 :             async move {
    2757            0 :                 let new_metadata = TimelineMetadata::new(
    2758            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2759            0 :                     // make it valid, before calling finish_creation()
    2760            0 :                     Lsn(0),
    2761            0 :                     None,
    2762            0 :                     None,
    2763            0 :                     Lsn(0),
    2764            0 :                     initdb_lsn,
    2765            0 :                     initdb_lsn,
    2766            0 :                     15,
    2767            0 :                 );
    2768            0 :                 this.prepare_new_timeline(
    2769            0 :                     new_timeline_id,
    2770            0 :                     &new_metadata,
    2771            0 :                     timeline_create_guard,
    2772            0 :                     initdb_lsn,
    2773            0 :                     None,
    2774            0 :                 )
    2775            0 :                 .await
    2776            0 :             }
    2777            0 :         }
    2778            0 :         .await?;
    2779              : 
    2780            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2781            0 :             idempotency_key,
    2782            0 :             location,
    2783            0 :             started_at,
    2784            0 :         };
    2785            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2786            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2787            0 :         );
    2788            0 :         uninit_timeline
    2789            0 :             .raw_timeline()
    2790            0 :             .unwrap()
    2791            0 :             .remote_client
    2792            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2793              : 
    2794              :         // wait_completion happens in caller
    2795              : 
    2796            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2797            0 : 
    2798            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2799            0 :             timeline.clone(),
    2800            0 :             index_part,
    2801            0 :             activate,
    2802            0 :             timeline_create_guard,
    2803            0 :         ));
    2804            0 : 
    2805            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2806            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2807            0 :     }
    2808              : 
    2809              :     #[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))]
    2810              :     async fn create_timeline_import_pgdata_task(
    2811              :         self: Arc<Tenant>,
    2812              :         timeline: Arc<Timeline>,
    2813              :         index_part: import_pgdata::index_part_format::Root,
    2814              :         activate: ActivateTimelineArgs,
    2815              :         timeline_create_guard: TimelineCreateGuard,
    2816              :     ) {
    2817              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2818              :         info!("starting");
    2819              :         scopeguard::defer! {info!("exiting")};
    2820              : 
    2821              :         let res = self
    2822              :             .create_timeline_import_pgdata_task_impl(
    2823              :                 timeline,
    2824              :                 index_part,
    2825              :                 activate,
    2826              :                 timeline_create_guard,
    2827              :             )
    2828              :             .await;
    2829              :         if let Err(err) = &res {
    2830              :             error!(?err, "task failed");
    2831              :             // TODO sleep & retry, sensitive to tenant shutdown
    2832              :             // TODO: allow timeline deletion requests => should cancel the task
    2833              :         }
    2834              :     }
    2835              : 
    2836            0 :     async fn create_timeline_import_pgdata_task_impl(
    2837            0 :         self: Arc<Tenant>,
    2838            0 :         timeline: Arc<Timeline>,
    2839            0 :         index_part: import_pgdata::index_part_format::Root,
    2840            0 :         activate: ActivateTimelineArgs,
    2841            0 :         timeline_create_guard: TimelineCreateGuard,
    2842            0 :     ) -> Result<(), anyhow::Error> {
    2843            0 :         let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
    2844            0 : 
    2845            0 :         info!("importing pgdata");
    2846            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2847            0 :             .await
    2848            0 :             .context("import")?;
    2849            0 :         info!("import done");
    2850              : 
    2851              :         //
    2852              :         // Reload timeline from remote.
    2853              :         // This proves that the remote state is attachable, and it reuses the code.
    2854              :         //
    2855              :         // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
    2856              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2857              :         // But our activate() call might launch new background tasks after Tenant::shutdown
    2858              :         // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
    2859              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2860              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2861              :         // to manifest because of the long runtime of this import task.
    2862              : 
    2863              :         //        in theory this shouldn't even .await anything except for coop yield
    2864            0 :         info!("shutting down timeline");
    2865            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2866            0 :         info!("timeline shut down, reloading from remote");
    2867              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2868              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2869              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2870              :         // };
    2871            0 :         let timeline_id = timeline.timeline_id;
    2872            0 : 
    2873            0 :         // load from object storage like Tenant::attach does
    2874            0 :         let resources = self.build_timeline_resources(timeline_id);
    2875            0 :         let index_part = resources
    2876            0 :             .remote_client
    2877            0 :             .download_index_file(&self.cancel)
    2878            0 :             .await?;
    2879            0 :         let index_part = match index_part {
    2880              :             MaybeDeletedIndexPart::Deleted(_) => {
    2881              :                 // likely concurrent delete call, cplane should prevent this
    2882            0 :                 anyhow::bail!(
    2883            0 :                     "index part says deleted but we are not done creating yet, this should not happen but"
    2884            0 :                 )
    2885              :             }
    2886            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2887            0 :         };
    2888            0 :         let metadata = index_part.metadata.clone();
    2889            0 :         self
    2890            0 :             .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
    2891            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2892            0 :             .await?
    2893            0 :             .ready_to_activate()
    2894            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2895              : 
    2896            0 :         anyhow::Ok(())
    2897            0 :     }
    2898              : 
    2899            0 :     pub(crate) async fn delete_timeline(
    2900            0 :         self: Arc<Self>,
    2901            0 :         timeline_id: TimelineId,
    2902            0 :     ) -> Result<(), DeleteTimelineError> {
    2903            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2904              : 
    2905            0 :         Ok(())
    2906            0 :     }
    2907              : 
    2908              :     /// perform one garbage collection iteration, removing old data files from disk.
    2909              :     /// this function is periodically called by gc task.
    2910              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2911              :     ///
    2912              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2913              :     ///
    2914              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2915              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2916              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2917              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2918              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2919              :     /// requires more history to be retained.
    2920              :     //
    2921         1508 :     pub(crate) async fn gc_iteration(
    2922         1508 :         &self,
    2923         1508 :         target_timeline_id: Option<TimelineId>,
    2924         1508 :         horizon: u64,
    2925         1508 :         pitr: Duration,
    2926         1508 :         cancel: &CancellationToken,
    2927         1508 :         ctx: &RequestContext,
    2928         1508 :     ) -> Result<GcResult, GcError> {
    2929         1508 :         // Don't start doing work during shutdown
    2930         1508 :         if let TenantState::Stopping { .. } = self.current_state() {
    2931            0 :             return Ok(GcResult::default());
    2932         1508 :         }
    2933         1508 : 
    2934         1508 :         // there is a global allowed_error for this
    2935         1508 :         if !self.is_active() {
    2936            0 :             return Err(GcError::NotActive);
    2937         1508 :         }
    2938         1508 : 
    2939         1508 :         {
    2940         1508 :             let conf = self.tenant_conf.load();
    2941         1508 : 
    2942         1508 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2943         1508 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2944         1508 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2945         1508 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2946         1508 :             if !conf.location.may_delete_layers_hint() {
    2947            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2948            0 :                 return Ok(GcResult::default());
    2949         1508 :             }
    2950         1508 : 
    2951         1508 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2952         1500 :                 info!("Skipping GC because lsn lease deadline is not reached");
    2953         1500 :                 return Ok(GcResult::default());
    2954            8 :             }
    2955              :         }
    2956              : 
    2957            8 :         let _guard = match self.gc_block.start().await {
    2958            8 :             Ok(guard) => guard,
    2959            0 :             Err(reasons) => {
    2960            0 :                 info!("Skipping GC: {reasons}");
    2961            0 :                 return Ok(GcResult::default());
    2962              :             }
    2963              :         };
    2964              : 
    2965            8 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    2966            8 :             .await
    2967         1508 :     }
    2968              : 
    2969              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    2970              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    2971              :     /// immediate L0 compaction.
    2972              :     ///
    2973              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    2974            0 :     async fn compaction_iteration(
    2975            0 :         self: &Arc<Self>,
    2976            0 :         cancel: &CancellationToken,
    2977            0 :         ctx: &RequestContext,
    2978            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    2979            0 :         // Don't compact inactive tenants.
    2980            0 :         if !self.is_active() {
    2981            0 :             return Ok(CompactionOutcome::Skipped);
    2982            0 :         }
    2983            0 : 
    2984            0 :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    2985            0 :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    2986            0 :         let location = self.tenant_conf.load().location;
    2987            0 :         if !location.may_upload_layers_hint() {
    2988            0 :             info!("skipping compaction in location state {location:?}");
    2989            0 :             return Ok(CompactionOutcome::Skipped);
    2990            0 :         }
    2991            0 : 
    2992            0 :         // Don't compact if the circuit breaker is tripped.
    2993            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    2994            0 :             info!("skipping compaction due to previous failures");
    2995            0 :             return Ok(CompactionOutcome::Skipped);
    2996            0 :         }
    2997            0 : 
    2998            0 :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    2999            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3000            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3001            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3002            0 : 
    3003            0 :         {
    3004            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3005            0 :             let timelines = self.timelines.lock().unwrap();
    3006            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3007              :                 // Skip inactive timelines.
    3008            0 :                 if !timeline.is_active() {
    3009            0 :                     continue;
    3010            0 :                 }
    3011            0 : 
    3012            0 :                 // Schedule the timeline for compaction.
    3013            0 :                 compact.push(timeline.clone());
    3014              : 
    3015              :                 // Schedule the timeline for offloading if eligible.
    3016            0 :                 let can_offload = offload_enabled
    3017            0 :                     && timeline.can_offload().0
    3018            0 :                     && !timelines
    3019            0 :                         .iter()
    3020            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3021            0 :                 if can_offload {
    3022            0 :                     offload.insert(timeline_id);
    3023            0 :                 }
    3024              :             }
    3025              :         } // release timelines lock
    3026              : 
    3027            0 :         for timeline in &compact {
    3028              :             // Collect L0 counts. Can't await while holding lock above.
    3029            0 :             if let Ok(lm) = timeline.layers.read().await.layer_map() {
    3030            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3031            0 :             }
    3032              :         }
    3033              : 
    3034              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3035              :         // bound read amplification.
    3036              :         //
    3037              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3038              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3039              :         // splitting L0 and image/GC compaction to separate background jobs.
    3040            0 :         if self.get_compaction_l0_first() {
    3041            0 :             let compaction_threshold = self.get_compaction_threshold();
    3042            0 :             let compact_l0 = compact
    3043            0 :                 .iter()
    3044            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3045            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3046            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3047            0 :                 .rev()
    3048            0 :                 .map(|(tli, _)| tli.clone())
    3049            0 :                 .collect_vec();
    3050            0 : 
    3051            0 :             let mut has_pending_l0 = false;
    3052            0 :             for timeline in compact_l0 {
    3053            0 :                 let outcome = timeline
    3054            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3055            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3056            0 :                     .await
    3057            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3058            0 :                 match outcome {
    3059            0 :                     CompactionOutcome::Done => {}
    3060            0 :                     CompactionOutcome::Skipped => {}
    3061            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3062            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3063              :                 }
    3064              :             }
    3065            0 :             if has_pending_l0 {
    3066            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3067            0 :             }
    3068            0 :         }
    3069              : 
    3070              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated
    3071              :         // more L0 layers, they may also be compacted here.
    3072              :         //
    3073              :         // NB: image compaction may yield if there is pending L0 compaction.
    3074              :         //
    3075              :         // TODO: it will only yield if there is pending L0 compaction on the same timeline. If a
    3076              :         // different timeline needs compaction, it won't. It should check `l0_compaction_trigger`.
    3077              :         // We leave this for a later PR.
    3078              :         //
    3079              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3080              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3081            0 :         let mut has_pending = false;
    3082            0 :         for timeline in compact {
    3083            0 :             if !timeline.is_active() {
    3084            0 :                 continue;
    3085            0 :             }
    3086              : 
    3087            0 :             let mut outcome = timeline
    3088            0 :                 .compact(cancel, EnumSet::default(), ctx)
    3089            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3090            0 :                 .await
    3091            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3092              : 
    3093              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3094            0 :             if outcome == CompactionOutcome::Done {
    3095            0 :                 let queue = {
    3096            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3097            0 :                     guard
    3098            0 :                         .entry(timeline.timeline_id)
    3099            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3100            0 :                         .clone()
    3101            0 :                 };
    3102            0 :                 outcome = queue
    3103            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3104            0 :                     .instrument(
    3105            0 :                         info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
    3106              :                     )
    3107            0 :                     .await?;
    3108            0 :             }
    3109              : 
    3110              :             // If we're done compacting, offload the timeline if requested.
    3111            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3112            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3113            0 :                 offload_timeline(self, &timeline)
    3114            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3115            0 :                     .await
    3116            0 :                     .or_else(|err| match err {
    3117              :                         // Ignore this, we likely raced with unarchival.
    3118            0 :                         OffloadError::NotArchived => Ok(()),
    3119            0 :                         err => Err(err),
    3120            0 :                     })?;
    3121            0 :             }
    3122              : 
    3123            0 :             match outcome {
    3124            0 :                 CompactionOutcome::Done => {}
    3125            0 :                 CompactionOutcome::Skipped => {}
    3126            0 :                 CompactionOutcome::Pending => has_pending = true,
    3127              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3128              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3129            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3130              :             }
    3131              :         }
    3132              : 
    3133              :         // Success! Untrip the breaker if necessary.
    3134            0 :         self.compaction_circuit_breaker
    3135            0 :             .lock()
    3136            0 :             .unwrap()
    3137            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3138            0 : 
    3139            0 :         match has_pending {
    3140            0 :             true => Ok(CompactionOutcome::Pending),
    3141            0 :             false => Ok(CompactionOutcome::Done),
    3142              :         }
    3143            0 :     }
    3144              : 
    3145              :     /// Trips the compaction circuit breaker if appropriate.
    3146            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3147            0 :         match err {
    3148            0 :             err if err.is_cancel() => {}
    3149            0 :             CompactionError::ShuttingDown => (),
    3150              :             // Offload failures don't trip the circuit breaker, since they're cheap to retry and
    3151              :             // shouldn't block compaction.
    3152            0 :             CompactionError::Offload(_) => {}
    3153            0 :             CompactionError::CollectKeySpaceError(err) => {
    3154            0 :                 // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
    3155            0 :                 self.compaction_circuit_breaker
    3156            0 :                     .lock()
    3157            0 :                     .unwrap()
    3158            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3159            0 :             }
    3160            0 :             CompactionError::Other(err) => {
    3161            0 :                 self.compaction_circuit_breaker
    3162            0 :                     .lock()
    3163            0 :                     .unwrap()
    3164            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3165            0 :             }
    3166            0 :             CompactionError::AlreadyRunning(_) => {}
    3167              :         }
    3168            0 :     }
    3169              : 
    3170              :     /// Cancel scheduled compaction tasks
    3171            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3172            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3173            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3174            0 :             q.cancel_scheduled();
    3175            0 :         }
    3176            0 :     }
    3177              : 
    3178            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3179            0 :         &self,
    3180            0 :         timeline_id: TimelineId,
    3181            0 :     ) -> Vec<CompactInfoResponse> {
    3182            0 :         let res = {
    3183            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3184            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3185              :         };
    3186            0 :         let Some((running, remaining)) = res else {
    3187            0 :             return Vec::new();
    3188              :         };
    3189            0 :         let mut result = Vec::new();
    3190            0 :         if let Some((id, running)) = running {
    3191            0 :             result.extend(running.into_compact_info_resp(id, true));
    3192            0 :         }
    3193            0 :         for (id, job) in remaining {
    3194            0 :             result.extend(job.into_compact_info_resp(id, false));
    3195            0 :         }
    3196            0 :         result
    3197            0 :     }
    3198              : 
    3199              :     /// Schedule a compaction task for a timeline.
    3200            0 :     pub(crate) async fn schedule_compaction(
    3201            0 :         &self,
    3202            0 :         timeline_id: TimelineId,
    3203            0 :         options: CompactOptions,
    3204            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3205            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3206            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3207            0 :         let q = guard
    3208            0 :             .entry(timeline_id)
    3209            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3210            0 :         q.schedule_manual_compaction(options, Some(tx));
    3211            0 :         Ok(rx)
    3212            0 :     }
    3213              : 
    3214              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3215            0 :     async fn housekeeping(&self) {
    3216            0 :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3217            0 :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3218            0 :         let timelines = self
    3219            0 :             .timelines
    3220            0 :             .lock()
    3221            0 :             .unwrap()
    3222            0 :             .values()
    3223            0 :             .filter(|tli| tli.is_active())
    3224            0 :             .cloned()
    3225            0 :             .collect_vec();
    3226              : 
    3227            0 :         for timeline in timelines {
    3228            0 :             timeline.maybe_freeze_ephemeral_layer().await;
    3229              :         }
    3230              : 
    3231              :         // Shut down walredo if idle.
    3232              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3233            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3234            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3235            0 :         }
    3236            0 :     }
    3237              : 
    3238            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3239            0 :         let timelines = self.timelines.lock().unwrap();
    3240            0 :         !timelines
    3241            0 :             .iter()
    3242            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3243            0 :     }
    3244              : 
    3245         3468 :     pub fn current_state(&self) -> TenantState {
    3246         3468 :         self.state.borrow().clone()
    3247         3468 :     }
    3248              : 
    3249         1944 :     pub fn is_active(&self) -> bool {
    3250         1944 :         self.current_state() == TenantState::Active
    3251         1944 :     }
    3252              : 
    3253            0 :     pub fn generation(&self) -> Generation {
    3254            0 :         self.generation
    3255            0 :     }
    3256              : 
    3257            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3258            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3259            0 :     }
    3260              : 
    3261              :     /// Changes tenant status to active, unless shutdown was already requested.
    3262              :     ///
    3263              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3264              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3265            0 :     fn activate(
    3266            0 :         self: &Arc<Self>,
    3267            0 :         broker_client: BrokerClientChannel,
    3268            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3269            0 :         ctx: &RequestContext,
    3270            0 :     ) {
    3271            0 :         span::debug_assert_current_span_has_tenant_id();
    3272            0 : 
    3273            0 :         let mut activating = false;
    3274            0 :         self.state.send_modify(|current_state| {
    3275              :             use pageserver_api::models::ActivatingFrom;
    3276            0 :             match &*current_state {
    3277              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3278            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3279              :                 }
    3280            0 :                 TenantState::Attaching => {
    3281            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3282            0 :                 }
    3283            0 :             }
    3284            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3285            0 :             activating = true;
    3286            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3287            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3288            0 :         });
    3289            0 : 
    3290            0 :         if activating {
    3291            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3292            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3293            0 :             let timelines_to_activate = timelines_accessor
    3294            0 :                 .values()
    3295            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3296            0 : 
    3297            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3298            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3299            0 : 
    3300            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3301            0 :             // down when they notice that the tenant is inactive.
    3302            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3303            0 : 
    3304            0 :             let mut activated_timelines = 0;
    3305              : 
    3306            0 :             for timeline in timelines_to_activate {
    3307            0 :                 timeline.activate(
    3308            0 :                     self.clone(),
    3309            0 :                     broker_client.clone(),
    3310            0 :                     background_jobs_can_start,
    3311            0 :                     ctx,
    3312            0 :                 );
    3313            0 :                 activated_timelines += 1;
    3314            0 :             }
    3315              : 
    3316            0 :             self.state.send_modify(move |current_state| {
    3317            0 :                 assert!(
    3318            0 :                     matches!(current_state, TenantState::Activating(_)),
    3319            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3320              :                 );
    3321            0 :                 *current_state = TenantState::Active;
    3322            0 : 
    3323            0 :                 let elapsed = self.constructed_at.elapsed();
    3324            0 :                 let total_timelines = timelines_accessor.len();
    3325            0 : 
    3326            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3327            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3328            0 :                 info!(
    3329            0 :                     since_creation_millis = elapsed.as_millis(),
    3330            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3331            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3332            0 :                     activated_timelines,
    3333            0 :                     total_timelines,
    3334            0 :                     post_state = <&'static str>::from(&*current_state),
    3335            0 :                     "activation attempt finished"
    3336              :                 );
    3337              : 
    3338            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3339            0 :             });
    3340            0 :         }
    3341            0 :     }
    3342              : 
    3343              :     /// Shutdown the tenant and join all of the spawned tasks.
    3344              :     ///
    3345              :     /// The method caters for all use-cases:
    3346              :     /// - pageserver shutdown (freeze_and_flush == true)
    3347              :     /// - detach + ignore (freeze_and_flush == false)
    3348              :     ///
    3349              :     /// This will attempt to shutdown even if tenant is broken.
    3350              :     ///
    3351              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3352              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3353              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3354              :     /// the ongoing shutdown.
    3355           12 :     async fn shutdown(
    3356           12 :         &self,
    3357           12 :         shutdown_progress: completion::Barrier,
    3358           12 :         shutdown_mode: timeline::ShutdownMode,
    3359           12 :     ) -> Result<(), completion::Barrier> {
    3360           12 :         span::debug_assert_current_span_has_tenant_id();
    3361              : 
    3362              :         // Set tenant (and its timlines) to Stoppping state.
    3363              :         //
    3364              :         // Since we can only transition into Stopping state after activation is complete,
    3365              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3366              :         //
    3367              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3368              :         // 1. Lock out any new requests to the tenants.
    3369              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3370              :         // 3. Signal cancellation for other tenant background loops.
    3371              :         // 4. ???
    3372              :         //
    3373              :         // The waiting for the cancellation is not done uniformly.
    3374              :         // We certainly wait for WAL receivers to shut down.
    3375              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3376              :         // But the tenant background loops are joined-on in our caller.
    3377              :         // It's mesed up.
    3378              :         // we just ignore the failure to stop
    3379              : 
    3380              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3381              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3382              :         // is very slow.
    3383           12 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3384            0 :             self.cancel.cancel();
    3385            0 : 
    3386            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3387            0 :             // are children of ours, so their flush loops will have shut down already
    3388            0 :             timeline::ShutdownMode::Hard
    3389              :         } else {
    3390           12 :             shutdown_mode
    3391              :         };
    3392              : 
    3393           12 :         match self.set_stopping(shutdown_progress, false, false).await {
    3394           12 :             Ok(()) => {}
    3395            0 :             Err(SetStoppingError::Broken) => {
    3396            0 :                 // assume that this is acceptable
    3397            0 :             }
    3398            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3399            0 :                 // give caller the option to wait for this this shutdown
    3400            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3401            0 :                 return Err(other);
    3402              :             }
    3403              :         };
    3404              : 
    3405           12 :         let mut js = tokio::task::JoinSet::new();
    3406           12 :         {
    3407           12 :             let timelines = self.timelines.lock().unwrap();
    3408           12 :             timelines.values().for_each(|timeline| {
    3409           12 :                 let timeline = Arc::clone(timeline);
    3410           12 :                 let timeline_id = timeline.timeline_id;
    3411           12 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3412           12 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3413           12 :             });
    3414           12 :         }
    3415           12 :         {
    3416           12 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3417           12 :             timelines_offloaded.values().for_each(|timeline| {
    3418            0 :                 timeline.defuse_for_tenant_drop();
    3419           12 :             });
    3420           12 :         }
    3421           12 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3422           12 :         tracing::info!("Waiting for timelines...");
    3423           24 :         while let Some(res) = js.join_next().await {
    3424            0 :             match res {
    3425           12 :                 Ok(()) => {}
    3426            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3427            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3428            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3429              :             }
    3430              :         }
    3431              : 
    3432           12 :         if let ShutdownMode::Reload = shutdown_mode {
    3433            0 :             tracing::info!("Flushing deletion queue");
    3434            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3435            0 :                 match e {
    3436            0 :                     DeletionQueueError::ShuttingDown => {
    3437            0 :                         // This is the only error we expect for now. In the future, if more error
    3438            0 :                         // variants are added, we should handle them here.
    3439            0 :                     }
    3440              :                 }
    3441            0 :             }
    3442           12 :         }
    3443              : 
    3444              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3445              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3446           12 :         tracing::debug!("Cancelling CancellationToken");
    3447           12 :         self.cancel.cancel();
    3448           12 : 
    3449           12 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3450           12 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3451           12 :         //
    3452           12 :         // this will additionally shutdown and await all timeline tasks.
    3453           12 :         tracing::debug!("Waiting for tasks...");
    3454           12 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3455              : 
    3456           12 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3457           12 :             walredo_mgr.shutdown().await;
    3458            0 :         }
    3459              : 
    3460              :         // Wait for any in-flight operations to complete
    3461           12 :         self.gate.close().await;
    3462              : 
    3463           12 :         remove_tenant_metrics(&self.tenant_shard_id);
    3464           12 : 
    3465           12 :         Ok(())
    3466           12 :     }
    3467              : 
    3468              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3469              :     ///
    3470              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3471              :     ///
    3472              :     /// This function is not cancel-safe!
    3473              :     ///
    3474              :     /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
    3475              :     /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
    3476           12 :     async fn set_stopping(
    3477           12 :         &self,
    3478           12 :         progress: completion::Barrier,
    3479           12 :         _allow_transition_from_loading: bool,
    3480           12 :         allow_transition_from_attaching: bool,
    3481           12 :     ) -> Result<(), SetStoppingError> {
    3482           12 :         let mut rx = self.state.subscribe();
    3483           12 : 
    3484           12 :         // cannot stop before we're done activating, so wait out until we're done activating
    3485           12 :         rx.wait_for(|state| match state {
    3486            0 :             TenantState::Attaching if allow_transition_from_attaching => true,
    3487              :             TenantState::Activating(_) | TenantState::Attaching => {
    3488            0 :                 info!(
    3489            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3490            0 :                     <&'static str>::from(state)
    3491              :                 );
    3492            0 :                 false
    3493              :             }
    3494           12 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3495           12 :         })
    3496           12 :         .await
    3497           12 :         .expect("cannot drop self.state while on a &self method");
    3498           12 : 
    3499           12 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3500           12 :         let mut err = None;
    3501           12 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3502              :             TenantState::Activating(_) => {
    3503            0 :                 unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
    3504              :             }
    3505              :             TenantState::Attaching => {
    3506            0 :                 if !allow_transition_from_attaching {
    3507            0 :                     unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
    3508            0 :                 };
    3509            0 :                 *current_state = TenantState::Stopping { progress };
    3510            0 :                 true
    3511              :             }
    3512              :             TenantState::Active => {
    3513              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3514              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3515              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3516           12 :                 *current_state = TenantState::Stopping { progress };
    3517           12 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3518           12 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3519           12 :                 true
    3520              :             }
    3521            0 :             TenantState::Broken { reason, .. } => {
    3522            0 :                 info!(
    3523            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3524              :                 );
    3525            0 :                 err = Some(SetStoppingError::Broken);
    3526            0 :                 false
    3527              :             }
    3528            0 :             TenantState::Stopping { progress } => {
    3529            0 :                 info!("Tenant is already in Stopping state");
    3530            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3531            0 :                 false
    3532              :             }
    3533           12 :         });
    3534           12 :         match (stopping, err) {
    3535           12 :             (true, None) => {} // continue
    3536            0 :             (false, Some(err)) => return Err(err),
    3537            0 :             (true, Some(_)) => unreachable!(
    3538            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3539            0 :             ),
    3540            0 :             (false, None) => unreachable!(
    3541            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3542            0 :             ),
    3543              :         }
    3544              : 
    3545           12 :         let timelines_accessor = self.timelines.lock().unwrap();
    3546           12 :         let not_broken_timelines = timelines_accessor
    3547           12 :             .values()
    3548           12 :             .filter(|timeline| !timeline.is_broken());
    3549           24 :         for timeline in not_broken_timelines {
    3550           12 :             timeline.set_state(TimelineState::Stopping);
    3551           12 :         }
    3552           12 :         Ok(())
    3553           12 :     }
    3554              : 
    3555              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3556              :     /// `remove_tenant_from_memory`
    3557              :     ///
    3558              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3559              :     ///
    3560              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3561            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3562            0 :         let mut rx = self.state.subscribe();
    3563            0 : 
    3564            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3565            0 :         // So, wait until it's done.
    3566            0 :         rx.wait_for(|state| match state {
    3567              :             TenantState::Activating(_) | TenantState::Attaching => {
    3568            0 :                 info!(
    3569            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3570            0 :                     <&'static str>::from(state)
    3571              :                 );
    3572            0 :                 false
    3573              :             }
    3574            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3575            0 :         })
    3576            0 :         .await
    3577            0 :         .expect("cannot drop self.state while on a &self method");
    3578            0 : 
    3579            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3580            0 :         self.set_broken_no_wait(reason)
    3581            0 :     }
    3582              : 
    3583            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3584            0 :         let reason = reason.to_string();
    3585            0 :         self.state.send_modify(|current_state| {
    3586            0 :             match *current_state {
    3587              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3588            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3589              :                 }
    3590              :                 TenantState::Active => {
    3591            0 :                     if cfg!(feature = "testing") {
    3592            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3593            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3594              :                     } else {
    3595            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3596              :                     }
    3597              :                 }
    3598              :                 TenantState::Broken { .. } => {
    3599            0 :                     warn!("Tenant is already in Broken state");
    3600              :                 }
    3601              :                 // This is the only "expected" path, any other path is a bug.
    3602              :                 TenantState::Stopping { .. } => {
    3603            0 :                     warn!(
    3604            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3605              :                         reason
    3606              :                     );
    3607            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3608              :                 }
    3609              :            }
    3610            0 :         });
    3611            0 :     }
    3612              : 
    3613            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3614            0 :         self.state.subscribe()
    3615            0 :     }
    3616              : 
    3617              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3618              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3619            0 :     pub(crate) fn activate_now(&self) {
    3620            0 :         self.activate_now_sem.add_permits(1);
    3621            0 :     }
    3622              : 
    3623            0 :     pub(crate) async fn wait_to_become_active(
    3624            0 :         &self,
    3625            0 :         timeout: Duration,
    3626            0 :     ) -> Result<(), GetActiveTenantError> {
    3627            0 :         let mut receiver = self.state.subscribe();
    3628              :         loop {
    3629            0 :             let current_state = receiver.borrow_and_update().clone();
    3630            0 :             match current_state {
    3631              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3632              :                     // in these states, there's a chance that we can reach ::Active
    3633            0 :                     self.activate_now();
    3634            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3635            0 :                         Ok(r) => {
    3636            0 :                             r.map_err(
    3637            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3638              :                                 // Tenant existed but was dropped: report it as non-existent
    3639            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3640            0 :                         )?
    3641              :                         }
    3642              :                         Err(TimeoutCancellableError::Cancelled) => {
    3643            0 :                             return Err(GetActiveTenantError::Cancelled);
    3644              :                         }
    3645              :                         Err(TimeoutCancellableError::Timeout) => {
    3646            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3647            0 :                                 latest_state: Some(self.current_state()),
    3648            0 :                                 wait_time: timeout,
    3649            0 :                             });
    3650              :                         }
    3651              :                     }
    3652              :                 }
    3653              :                 TenantState::Active { .. } => {
    3654            0 :                     return Ok(());
    3655              :                 }
    3656            0 :                 TenantState::Broken { reason, .. } => {
    3657            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3658            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3659            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3660              :                 }
    3661              :                 TenantState::Stopping { .. } => {
    3662              :                     // There's no chance the tenant can transition back into ::Active
    3663            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3664              :                 }
    3665              :             }
    3666              :         }
    3667            0 :     }
    3668              : 
    3669            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3670            0 :         self.tenant_conf.load().location.attach_mode
    3671            0 :     }
    3672              : 
    3673              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3674              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3675              :     /// rare external API calls, like a reconciliation at startup.
    3676            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3677            0 :         let conf = self.tenant_conf.load();
    3678              : 
    3679            0 :         let location_config_mode = match conf.location.attach_mode {
    3680            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3681            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3682            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3683              :         };
    3684              : 
    3685              :         // We have a pageserver TenantConf, we need the API-facing TenantConfig.
    3686            0 :         let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
    3687            0 : 
    3688            0 :         models::LocationConfig {
    3689            0 :             mode: location_config_mode,
    3690            0 :             generation: self.generation.into(),
    3691            0 :             secondary_conf: None,
    3692            0 :             shard_number: self.shard_identity.number.0,
    3693            0 :             shard_count: self.shard_identity.count.literal(),
    3694            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3695            0 :             tenant_conf: tenant_config,
    3696            0 :         }
    3697            0 :     }
    3698              : 
    3699            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3700            0 :         &self.tenant_shard_id
    3701            0 :     }
    3702              : 
    3703            0 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3704            0 :         self.shard_identity.stripe_size
    3705            0 :     }
    3706              : 
    3707            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3708            0 :         self.generation
    3709            0 :     }
    3710              : 
    3711              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3712              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3713              :     /// resetting this tenant to a valid state if we fail.
    3714            0 :     pub(crate) async fn split_prepare(
    3715            0 :         &self,
    3716            0 :         child_shards: &Vec<TenantShardId>,
    3717            0 :     ) -> anyhow::Result<()> {
    3718            0 :         let (timelines, offloaded) = {
    3719            0 :             let timelines = self.timelines.lock().unwrap();
    3720            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3721            0 :             (timelines.clone(), offloaded.clone())
    3722            0 :         };
    3723            0 :         let timelines_iter = timelines
    3724            0 :             .values()
    3725            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3726            0 :             .chain(
    3727            0 :                 offloaded
    3728            0 :                     .values()
    3729            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3730            0 :             );
    3731            0 :         for timeline in timelines_iter {
    3732              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3733              :             // to ensure that they do not start a split if currently in the process of doing these.
    3734              : 
    3735            0 :             let timeline_id = timeline.timeline_id();
    3736              : 
    3737            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3738              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3739              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3740              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3741            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3742            0 :                 timeline
    3743            0 :                     .remote_client
    3744            0 :                     .schedule_index_upload_for_file_changes()?;
    3745            0 :                 timeline.remote_client.wait_completion().await?;
    3746            0 :             }
    3747              : 
    3748            0 :             let remote_client = match timeline {
    3749            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3750            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3751            0 :                     let remote_client = self
    3752            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3753            0 :                     Arc::new(remote_client)
    3754              :                 }
    3755              :             };
    3756              : 
    3757              :             // Shut down the timeline's remote client: this means that the indices we write
    3758              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3759            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3760            0 :             remote_client.shutdown().await;
    3761              : 
    3762              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3763              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3764              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3765              :             // we use here really is the remotely persistent one).
    3766            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3767            0 :             let result = remote_client
    3768            0 :                 .download_index_file(&self.cancel)
    3769            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))
    3770            0 :                 .await?;
    3771            0 :             let index_part = match result {
    3772              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3773            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3774              :                 }
    3775            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3776              :             };
    3777              : 
    3778            0 :             for child_shard in child_shards {
    3779            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3780            0 :                 upload_index_part(
    3781            0 :                     &self.remote_storage,
    3782            0 :                     child_shard,
    3783            0 :                     &timeline_id,
    3784            0 :                     self.generation,
    3785            0 :                     &index_part,
    3786            0 :                     &self.cancel,
    3787            0 :                 )
    3788            0 :                 .await?;
    3789              :             }
    3790              :         }
    3791              : 
    3792            0 :         let tenant_manifest = self.build_tenant_manifest();
    3793            0 :         for child_shard in child_shards {
    3794            0 :             tracing::info!(
    3795            0 :                 "Uploading tenant manifest for child {}",
    3796            0 :                 child_shard.to_index()
    3797              :             );
    3798            0 :             upload_tenant_manifest(
    3799            0 :                 &self.remote_storage,
    3800            0 :                 child_shard,
    3801            0 :                 self.generation,
    3802            0 :                 &tenant_manifest,
    3803            0 :                 &self.cancel,
    3804            0 :             )
    3805            0 :             .await?;
    3806              :         }
    3807              : 
    3808            0 :         Ok(())
    3809            0 :     }
    3810              : 
    3811            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3812            0 :         let mut result = TopTenantShardItem {
    3813            0 :             id: self.tenant_shard_id,
    3814            0 :             resident_size: 0,
    3815            0 :             physical_size: 0,
    3816            0 :             max_logical_size: 0,
    3817            0 :         };
    3818              : 
    3819            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3820            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3821            0 : 
    3822            0 :             result.physical_size += timeline
    3823            0 :                 .remote_client
    3824            0 :                 .metrics
    3825            0 :                 .remote_physical_size_gauge
    3826            0 :                 .get();
    3827            0 :             result.max_logical_size = std::cmp::max(
    3828            0 :                 result.max_logical_size,
    3829            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3830            0 :             );
    3831            0 :         }
    3832              : 
    3833            0 :         result
    3834            0 :     }
    3835              : }
    3836              : 
    3837              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3838              : /// perform a topological sort, so that the parent of each timeline comes
    3839              : /// before the children.
    3840              : /// E extracts the ancestor from T
    3841              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3842          444 : fn tree_sort_timelines<T, E>(
    3843          444 :     timelines: HashMap<TimelineId, T>,
    3844          444 :     extractor: E,
    3845          444 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3846          444 : where
    3847          444 :     E: Fn(&T) -> Option<TimelineId>,
    3848          444 : {
    3849          444 :     let mut result = Vec::with_capacity(timelines.len());
    3850          444 : 
    3851          444 :     let mut now = Vec::with_capacity(timelines.len());
    3852          444 :     // (ancestor, children)
    3853          444 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3854          444 :         HashMap::with_capacity(timelines.len());
    3855              : 
    3856          456 :     for (timeline_id, value) in timelines {
    3857           12 :         if let Some(ancestor_id) = extractor(&value) {
    3858            4 :             let children = later.entry(ancestor_id).or_default();
    3859            4 :             children.push((timeline_id, value));
    3860            8 :         } else {
    3861            8 :             now.push((timeline_id, value));
    3862            8 :         }
    3863              :     }
    3864              : 
    3865          456 :     while let Some((timeline_id, metadata)) = now.pop() {
    3866           12 :         result.push((timeline_id, metadata));
    3867              :         // All children of this can be loaded now
    3868           12 :         if let Some(mut children) = later.remove(&timeline_id) {
    3869            4 :             now.append(&mut children);
    3870            8 :         }
    3871              :     }
    3872              : 
    3873              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3874          444 :     if !later.is_empty() {
    3875            0 :         for (missing_id, orphan_ids) in later {
    3876            0 :             for (orphan_id, _) in orphan_ids {
    3877            0 :                 error!(
    3878            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    3879              :                 );
    3880              :             }
    3881              :         }
    3882            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3883          444 :     }
    3884          444 : 
    3885          444 :     Ok(result)
    3886          444 : }
    3887              : 
    3888              : enum ActivateTimelineArgs {
    3889              :     Yes {
    3890              :         broker_client: storage_broker::BrokerClientChannel,
    3891              :     },
    3892              :     No,
    3893              : }
    3894              : 
    3895              : impl Tenant {
    3896            0 :     pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
    3897            0 :         self.tenant_conf.load().tenant_conf.clone()
    3898            0 :     }
    3899              : 
    3900            0 :     pub fn effective_config(&self) -> TenantConf {
    3901            0 :         self.tenant_specific_overrides()
    3902            0 :             .merge(self.conf.default_tenant_conf.clone())
    3903            0 :     }
    3904              : 
    3905            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3906            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3907            0 :         tenant_conf
    3908            0 :             .checkpoint_distance
    3909            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3910            0 :     }
    3911              : 
    3912            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3913            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3914            0 :         tenant_conf
    3915            0 :             .checkpoint_timeout
    3916            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3917            0 :     }
    3918              : 
    3919            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3920            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3921            0 :         tenant_conf
    3922            0 :             .compaction_target_size
    3923            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3924            0 :     }
    3925              : 
    3926            0 :     pub fn get_compaction_period(&self) -> Duration {
    3927            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3928            0 :         tenant_conf
    3929            0 :             .compaction_period
    3930            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3931            0 :     }
    3932              : 
    3933            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3934            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3935            0 :         tenant_conf
    3936            0 :             .compaction_threshold
    3937            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    3938            0 :     }
    3939              : 
    3940            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    3941            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3942            0 :         tenant_conf
    3943            0 :             .rel_size_v2_enabled
    3944            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    3945            0 :     }
    3946              : 
    3947            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    3948            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3949            0 :         tenant_conf
    3950            0 :             .compaction_upper_limit
    3951            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    3952            0 :     }
    3953              : 
    3954            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    3955            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3956            0 :         tenant_conf
    3957            0 :             .compaction_l0_first
    3958            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    3959            0 :     }
    3960              : 
    3961            0 :     pub fn get_gc_horizon(&self) -> u64 {
    3962            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3963            0 :         tenant_conf
    3964            0 :             .gc_horizon
    3965            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    3966            0 :     }
    3967              : 
    3968            0 :     pub fn get_gc_period(&self) -> Duration {
    3969            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3970            0 :         tenant_conf
    3971            0 :             .gc_period
    3972            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    3973            0 :     }
    3974              : 
    3975            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    3976            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3977            0 :         tenant_conf
    3978            0 :             .image_creation_threshold
    3979            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    3980            0 :     }
    3981              : 
    3982            0 :     pub fn get_pitr_interval(&self) -> Duration {
    3983            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3984            0 :         tenant_conf
    3985            0 :             .pitr_interval
    3986            0 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    3987            0 :     }
    3988              : 
    3989            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    3990            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3991            0 :         tenant_conf
    3992            0 :             .min_resident_size_override
    3993            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    3994            0 :     }
    3995              : 
    3996            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    3997            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3998            0 :         let heatmap_period = tenant_conf
    3999            0 :             .heatmap_period
    4000            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4001            0 :         if heatmap_period.is_zero() {
    4002            0 :             None
    4003              :         } else {
    4004            0 :             Some(heatmap_period)
    4005              :         }
    4006            0 :     }
    4007              : 
    4008            8 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4009            8 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4010            8 :         tenant_conf
    4011            8 :             .lsn_lease_length
    4012            8 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4013            8 :     }
    4014              : 
    4015            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4016            0 :         if self.conf.timeline_offloading {
    4017            0 :             return true;
    4018            0 :         }
    4019            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4020            0 :         tenant_conf
    4021            0 :             .timeline_offloading
    4022            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4023            0 :     }
    4024              : 
    4025              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4026            4 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4027            4 :         let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    4028            4 : 
    4029            4 :         let mut timeline_manifests = timelines_offloaded
    4030            4 :             .iter()
    4031            4 :             .map(|(_timeline_id, offloaded)| offloaded.manifest())
    4032            4 :             .collect::<Vec<_>>();
    4033            4 :         // Sort the manifests so that our output is deterministic
    4034            4 :         timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
    4035            4 : 
    4036            4 :         TenantManifest {
    4037            4 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4038            4 :             offloaded_timelines: timeline_manifests,
    4039            4 :         }
    4040            4 :     }
    4041              : 
    4042            0 :     pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
    4043            0 :         &self,
    4044            0 :         update: F,
    4045            0 :     ) -> anyhow::Result<TenantConfOpt> {
    4046            0 :         // Use read-copy-update in order to avoid overwriting the location config
    4047            0 :         // state if this races with [`Tenant::set_new_location_config`]. Note that
    4048            0 :         // this race is not possible if both request types come from the storage
    4049            0 :         // controller (as they should!) because an exclusive op lock is required
    4050            0 :         // on the storage controller side.
    4051            0 : 
    4052            0 :         self.tenant_conf
    4053            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4054            0 :                 Ok(Arc::new(AttachedTenantConf {
    4055            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4056            0 :                     location: attached_conf.location,
    4057            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4058              :                 }))
    4059            0 :             })?;
    4060              : 
    4061            0 :         let updated = self.tenant_conf.load();
    4062            0 : 
    4063            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    4064            0 :         // Don't hold self.timelines.lock() during the notifies.
    4065            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4066            0 :         // mutexes in struct Timeline in the future.
    4067            0 :         let timelines = self.list_timelines();
    4068            0 :         for timeline in timelines {
    4069            0 :             timeline.tenant_conf_updated(&updated);
    4070            0 :         }
    4071              : 
    4072            0 :         Ok(updated.tenant_conf.clone())
    4073            0 :     }
    4074              : 
    4075            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4076            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4077            0 : 
    4078            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4079            0 : 
    4080            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4081            0 :         // Don't hold self.timelines.lock() during the notifies.
    4082            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4083            0 :         // mutexes in struct Timeline in the future.
    4084            0 :         let timelines = self.list_timelines();
    4085            0 :         for timeline in timelines {
    4086            0 :             timeline.tenant_conf_updated(&new_conf);
    4087            0 :         }
    4088            0 :     }
    4089              : 
    4090          444 :     fn get_pagestream_throttle_config(
    4091          444 :         psconf: &'static PageServerConf,
    4092          444 :         overrides: &TenantConfOpt,
    4093          444 :     ) -> throttle::Config {
    4094          444 :         overrides
    4095          444 :             .timeline_get_throttle
    4096          444 :             .clone()
    4097          444 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4098          444 :     }
    4099              : 
    4100            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    4101            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4102            0 :         self.pagestream_throttle.reconfigure(conf)
    4103            0 :     }
    4104              : 
    4105              :     /// Helper function to create a new Timeline struct.
    4106              :     ///
    4107              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4108              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4109              :     /// map.
    4110              :     ///
    4111              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4112              :     /// and we might not have the ancestor present anymore which is fine for to be
    4113              :     /// deleted timelines.
    4114              :     #[allow(clippy::too_many_arguments)]
    4115          896 :     fn create_timeline_struct(
    4116          896 :         &self,
    4117          896 :         new_timeline_id: TimelineId,
    4118          896 :         new_metadata: &TimelineMetadata,
    4119          896 :         previous_heatmap: Option<PreviousHeatmap>,
    4120          896 :         ancestor: Option<Arc<Timeline>>,
    4121          896 :         resources: TimelineResources,
    4122          896 :         cause: CreateTimelineCause,
    4123          896 :         create_idempotency: CreateTimelineIdempotency,
    4124          896 :         gc_compaction_state: Option<GcCompactionState>,
    4125          896 :     ) -> anyhow::Result<Arc<Timeline>> {
    4126          896 :         let state = match cause {
    4127              :             CreateTimelineCause::Load => {
    4128          896 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4129          896 :                 anyhow::ensure!(
    4130          896 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4131            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4132              :                 );
    4133          896 :                 TimelineState::Loading
    4134              :             }
    4135            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4136              :         };
    4137              : 
    4138          896 :         let pg_version = new_metadata.pg_version();
    4139          896 : 
    4140          896 :         let timeline = Timeline::new(
    4141          896 :             self.conf,
    4142          896 :             Arc::clone(&self.tenant_conf),
    4143          896 :             new_metadata,
    4144          896 :             previous_heatmap,
    4145          896 :             ancestor,
    4146          896 :             new_timeline_id,
    4147          896 :             self.tenant_shard_id,
    4148          896 :             self.generation,
    4149          896 :             self.shard_identity,
    4150          896 :             self.walredo_mgr.clone(),
    4151          896 :             resources,
    4152          896 :             pg_version,
    4153          896 :             state,
    4154          896 :             self.attach_wal_lag_cooldown.clone(),
    4155          896 :             create_idempotency,
    4156          896 :             gc_compaction_state,
    4157          896 :             self.cancel.child_token(),
    4158          896 :         );
    4159          896 : 
    4160          896 :         Ok(timeline)
    4161          896 :     }
    4162              : 
    4163              :     /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
    4164              :     /// to ensure proper cleanup of background tasks and metrics.
    4165              :     //
    4166              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4167              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4168              :     #[allow(clippy::too_many_arguments)]
    4169          444 :     fn new(
    4170          444 :         state: TenantState,
    4171          444 :         conf: &'static PageServerConf,
    4172          444 :         attached_conf: AttachedTenantConf,
    4173          444 :         shard_identity: ShardIdentity,
    4174          444 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4175          444 :         tenant_shard_id: TenantShardId,
    4176          444 :         remote_storage: GenericRemoteStorage,
    4177          444 :         deletion_queue_client: DeletionQueueClient,
    4178          444 :         l0_flush_global_state: L0FlushGlobalState,
    4179          444 :     ) -> Tenant {
    4180          444 :         debug_assert!(
    4181          444 :             !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
    4182              :         );
    4183              : 
    4184          444 :         let (state, mut rx) = watch::channel(state);
    4185          444 : 
    4186          444 :         tokio::spawn(async move {
    4187          444 :             // reflect tenant state in metrics:
    4188          444 :             // - global per tenant state: TENANT_STATE_METRIC
    4189          444 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4190          444 :             //
    4191          444 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4192          444 :             // alerting.
    4193          444 : 
    4194          444 :             let tid = tenant_shard_id.to_string();
    4195          444 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4196          444 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4197              : 
    4198          888 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4199          888 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4200          888 :             }
    4201              : 
    4202          444 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4203          444 : 
    4204          444 :             let is_broken = tuple.1;
    4205          444 :             let mut counted_broken = if is_broken {
    4206              :                 // add the id to the set right away, there should not be any updates on the channel
    4207              :                 // after before tenant is removed, if ever
    4208            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4209            0 :                 true
    4210              :             } else {
    4211          444 :                 false
    4212              :             };
    4213              : 
    4214              :             loop {
    4215          888 :                 let labels = &tuple.0;
    4216          888 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4217          888 :                 current.inc();
    4218          888 : 
    4219          888 :                 if rx.changed().await.is_err() {
    4220              :                     // tenant has been dropped
    4221           28 :                     current.dec();
    4222           28 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4223           28 :                     break;
    4224          444 :                 }
    4225          444 : 
    4226          444 :                 current.dec();
    4227          444 :                 tuple = inspect_state(&rx.borrow_and_update());
    4228          444 : 
    4229          444 :                 let is_broken = tuple.1;
    4230          444 :                 if is_broken && !counted_broken {
    4231            0 :                     counted_broken = true;
    4232            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4233            0 :                     // access
    4234            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4235          444 :                 }
    4236              :             }
    4237          444 :         });
    4238          444 : 
    4239          444 :         Tenant {
    4240          444 :             tenant_shard_id,
    4241          444 :             shard_identity,
    4242          444 :             generation: attached_conf.location.generation,
    4243          444 :             conf,
    4244          444 :             // using now here is good enough approximation to catch tenants with really long
    4245          444 :             // activation times.
    4246          444 :             constructed_at: Instant::now(),
    4247          444 :             timelines: Mutex::new(HashMap::new()),
    4248          444 :             timelines_creating: Mutex::new(HashSet::new()),
    4249          444 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4250          444 :             tenant_manifest_upload: Default::default(),
    4251          444 :             gc_cs: tokio::sync::Mutex::new(()),
    4252          444 :             walredo_mgr,
    4253          444 :             remote_storage,
    4254          444 :             deletion_queue_client,
    4255          444 :             state,
    4256          444 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4257          444 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4258          444 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4259          444 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4260          444 :                 format!("compaction-{tenant_shard_id}"),
    4261          444 :                 5,
    4262          444 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4263          444 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4264          444 :                 // use an extremely long backoff.
    4265          444 :                 Some(Duration::from_secs(3600 * 24)),
    4266          444 :             )),
    4267          444 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4268          444 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4269          444 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4270          444 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4271          444 :             cancel: CancellationToken::default(),
    4272          444 :             gate: Gate::default(),
    4273          444 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4274          444 :                 Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4275          444 :             )),
    4276          444 :             pagestream_throttle_metrics: Arc::new(
    4277          444 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4278          444 :             ),
    4279          444 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4280          444 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4281          444 :             gc_block: Default::default(),
    4282          444 :             l0_flush_global_state,
    4283          444 :         }
    4284          444 :     }
    4285              : 
    4286              :     /// Locate and load config
    4287            0 :     pub(super) fn load_tenant_config(
    4288            0 :         conf: &'static PageServerConf,
    4289            0 :         tenant_shard_id: &TenantShardId,
    4290            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4291            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4292            0 : 
    4293            0 :         info!("loading tenant configuration from {config_path}");
    4294              : 
    4295              :         // load and parse file
    4296            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4297            0 :             match e.kind() {
    4298              :                 std::io::ErrorKind::NotFound => {
    4299              :                     // The config should almost always exist for a tenant directory:
    4300              :                     //  - When attaching a tenant, the config is the first thing we write
    4301              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4302              :                     //    before deleting contents.
    4303              :                     //
    4304              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4305              :                     // between creating directory and writing config.  Callers should handle that as if the
    4306              :                     // directory didn't exist.
    4307              : 
    4308            0 :                     LoadConfigError::NotFound(config_path)
    4309              :                 }
    4310              :                 _ => {
    4311              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4312              :                     // that we cannot cleanly recover
    4313            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4314              :                 }
    4315              :             }
    4316            0 :         })?;
    4317              : 
    4318            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4319            0 :     }
    4320              : 
    4321              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4322              :     pub(super) async fn persist_tenant_config(
    4323              :         conf: &'static PageServerConf,
    4324              :         tenant_shard_id: &TenantShardId,
    4325              :         location_conf: &LocationConf,
    4326              :     ) -> std::io::Result<()> {
    4327              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4328              : 
    4329              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4330              :     }
    4331              : 
    4332              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4333              :     pub(super) async fn persist_tenant_config_at(
    4334              :         tenant_shard_id: &TenantShardId,
    4335              :         config_path: &Utf8Path,
    4336              :         location_conf: &LocationConf,
    4337              :     ) -> std::io::Result<()> {
    4338              :         debug!("persisting tenantconf to {config_path}");
    4339              : 
    4340              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4341              : #  It is read in case of pageserver restart.
    4342              : "#
    4343              :         .to_string();
    4344              : 
    4345            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4346            0 :             Err(std::io::Error::new(
    4347            0 :                 std::io::ErrorKind::Other,
    4348            0 :                 "tenant-config-before-write",
    4349            0 :             ))
    4350            0 :         });
    4351              : 
    4352              :         // Convert the config to a toml file.
    4353              :         conf_content +=
    4354              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4355              : 
    4356              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4357              : 
    4358              :         let conf_content = conf_content.into_bytes();
    4359              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4360              :     }
    4361              : 
    4362              :     //
    4363              :     // How garbage collection works:
    4364              :     //
    4365              :     //                    +--bar------------->
    4366              :     //                   /
    4367              :     //             +----+-----foo---------------->
    4368              :     //            /
    4369              :     // ----main--+-------------------------->
    4370              :     //                \
    4371              :     //                 +-----baz-------->
    4372              :     //
    4373              :     //
    4374              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4375              :     //    `gc_infos` are being refreshed
    4376              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4377              :     //    all the points where other timelines have been branched off.
    4378              :     //    We will refrain from removing page versions at those LSNs.
    4379              :     // 3. For each timeline, scan all layer files on the timeline.
    4380              :     //    Remove all files for which a newer file exists and which
    4381              :     //    don't cover any branch point LSNs.
    4382              :     //
    4383              :     // TODO:
    4384              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4385              :     //   don't need to keep that in the parent anymore. But currently
    4386              :     //   we do.
    4387            8 :     async fn gc_iteration_internal(
    4388            8 :         &self,
    4389            8 :         target_timeline_id: Option<TimelineId>,
    4390            8 :         horizon: u64,
    4391            8 :         pitr: Duration,
    4392            8 :         cancel: &CancellationToken,
    4393            8 :         ctx: &RequestContext,
    4394            8 :     ) -> Result<GcResult, GcError> {
    4395            8 :         let mut totals: GcResult = Default::default();
    4396            8 :         let now = Instant::now();
    4397              : 
    4398            8 :         let gc_timelines = self
    4399            8 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4400            8 :             .await?;
    4401              : 
    4402            8 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4403              : 
    4404              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4405            8 :         if !gc_timelines.is_empty() {
    4406            8 :             info!("{} timelines need GC", gc_timelines.len());
    4407              :         } else {
    4408            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4409              :         }
    4410              : 
    4411              :         // Perform GC for each timeline.
    4412              :         //
    4413              :         // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
    4414              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4415              :         // with branch creation.
    4416              :         //
    4417              :         // See comments in [`Tenant::branch_timeline`] for more information about why branch
    4418              :         // creation task can run concurrently with timeline's GC iteration.
    4419           16 :         for timeline in gc_timelines {
    4420            8 :             if cancel.is_cancelled() {
    4421              :                 // We were requested to shut down. Stop and return with the progress we
    4422              :                 // made.
    4423            0 :                 break;
    4424            8 :             }
    4425            8 :             let result = match timeline.gc().await {
    4426              :                 Err(GcError::TimelineCancelled) => {
    4427            0 :                     if target_timeline_id.is_some() {
    4428              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4429            0 :                         return Err(GcError::TimelineCancelled);
    4430              :                     } else {
    4431              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4432              :                         // skip past this and proceed to try GC on other timelines.
    4433            0 :                         continue;
    4434              :                     }
    4435              :                 }
    4436            8 :                 r => r?,
    4437              :             };
    4438            8 :             totals += result;
    4439              :         }
    4440              : 
    4441            8 :         totals.elapsed = now.elapsed();
    4442            8 :         Ok(totals)
    4443            8 :     }
    4444              : 
    4445              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4446              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4447              :     /// [`Tenant::get_gc_horizon`].
    4448              :     ///
    4449              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4450            0 :     pub(crate) async fn refresh_gc_info(
    4451            0 :         &self,
    4452            0 :         cancel: &CancellationToken,
    4453            0 :         ctx: &RequestContext,
    4454            0 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4455            0 :         // since this method can now be called at different rates than the configured gc loop, it
    4456            0 :         // might be that these configuration values get applied faster than what it was previously,
    4457            0 :         // since these were only read from the gc task.
    4458            0 :         let horizon = self.get_gc_horizon();
    4459            0 :         let pitr = self.get_pitr_interval();
    4460            0 : 
    4461            0 :         // refresh all timelines
    4462            0 :         let target_timeline_id = None;
    4463            0 : 
    4464            0 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4465            0 :             .await
    4466            0 :     }
    4467              : 
    4468              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4469              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4470              :     ///
    4471              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4472            0 :     fn initialize_gc_info(
    4473            0 :         &self,
    4474            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4475            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4476            0 :         restrict_to_timeline: Option<TimelineId>,
    4477            0 :     ) {
    4478            0 :         if restrict_to_timeline.is_none() {
    4479              :             // This function must be called before activation: after activation timeline create/delete operations
    4480              :             // might happen, and this function is not safe to run concurrently with those.
    4481            0 :             assert!(!self.is_active());
    4482            0 :         }
    4483              : 
    4484              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4485              :         // the branch point where it was created.
    4486            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4487            0 :             BTreeMap::new();
    4488            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4489            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4490            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4491            0 :                 ancestor_children.push((
    4492            0 :                     timeline_entry.get_ancestor_lsn(),
    4493            0 :                     *timeline_id,
    4494            0 :                     MaybeOffloaded::No,
    4495            0 :                 ));
    4496            0 :             }
    4497            0 :         });
    4498            0 :         timelines_offloaded
    4499            0 :             .iter()
    4500            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4501            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4502            0 :                     return;
    4503              :                 };
    4504            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4505            0 :                     return;
    4506              :                 };
    4507            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4508            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4509            0 :             });
    4510            0 : 
    4511            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4512            0 :         let horizon = self.get_gc_horizon();
    4513              : 
    4514              :         // Populate each timeline's GcInfo with information about its child branches
    4515            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4516            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4517              :         } else {
    4518            0 :             itertools::Either::Right(timelines.values())
    4519              :         };
    4520            0 :         for timeline in timelines_to_write {
    4521            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4522            0 :                 .remove(&timeline.timeline_id)
    4523            0 :                 .unwrap_or_default();
    4524            0 : 
    4525            0 :             branchpoints.sort_by_key(|b| b.0);
    4526            0 : 
    4527            0 :             let mut target = timeline.gc_info.write().unwrap();
    4528            0 : 
    4529            0 :             target.retain_lsns = branchpoints;
    4530            0 : 
    4531            0 :             let space_cutoff = timeline
    4532            0 :                 .get_last_record_lsn()
    4533            0 :                 .checked_sub(horizon)
    4534            0 :                 .unwrap_or(Lsn(0));
    4535            0 : 
    4536            0 :             target.cutoffs = GcCutoffs {
    4537            0 :                 space: space_cutoff,
    4538            0 :                 time: Lsn::INVALID,
    4539            0 :             };
    4540            0 :         }
    4541            0 :     }
    4542              : 
    4543            8 :     async fn refresh_gc_info_internal(
    4544            8 :         &self,
    4545            8 :         target_timeline_id: Option<TimelineId>,
    4546            8 :         horizon: u64,
    4547            8 :         pitr: Duration,
    4548            8 :         cancel: &CancellationToken,
    4549            8 :         ctx: &RequestContext,
    4550            8 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4551            8 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4552            8 :         // currently visible timelines.
    4553            8 :         let timelines = self
    4554            8 :             .timelines
    4555            8 :             .lock()
    4556            8 :             .unwrap()
    4557            8 :             .values()
    4558            8 :             .filter(|tl| match target_timeline_id.as_ref() {
    4559            8 :                 Some(target) => &tl.timeline_id == target,
    4560            0 :                 None => true,
    4561            8 :             })
    4562            8 :             .cloned()
    4563            8 :             .collect::<Vec<_>>();
    4564            8 : 
    4565            8 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4566              :             // We were to act on a particular timeline and it wasn't found
    4567            0 :             return Err(GcError::TimelineNotFound);
    4568            8 :         }
    4569            8 : 
    4570            8 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4571            8 :             HashMap::with_capacity(timelines.len());
    4572            8 : 
    4573            8 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4574            8 :         let now_ts_for_pitr_calc = SystemTime::now();
    4575            8 :         for timeline in timelines.iter() {
    4576            8 :             let cutoff = timeline
    4577            8 :                 .get_last_record_lsn()
    4578            8 :                 .checked_sub(horizon)
    4579            8 :                 .unwrap_or(Lsn(0));
    4580              : 
    4581            8 :             let cutoffs = timeline
    4582            8 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4583            8 :                 .await?;
    4584            8 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4585            8 :             assert!(old.is_none());
    4586              :         }
    4587              : 
    4588            8 :         if !self.is_active() || self.cancel.is_cancelled() {
    4589            0 :             return Err(GcError::TenantCancelled);
    4590            8 :         }
    4591              : 
    4592              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4593              :         // because that will stall branch creation.
    4594            8 :         let gc_cs = self.gc_cs.lock().await;
    4595              : 
    4596              :         // Ok, we now know all the branch points.
    4597              :         // Update the GC information for each timeline.
    4598            8 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4599           16 :         for timeline in timelines {
    4600              :             // We filtered the timeline list above
    4601            8 :             if let Some(target_timeline_id) = target_timeline_id {
    4602            8 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4603            0 :             }
    4604              : 
    4605              :             {
    4606            8 :                 let mut target = timeline.gc_info.write().unwrap();
    4607            8 : 
    4608            8 :                 // Cull any expired leases
    4609            8 :                 let now = SystemTime::now();
    4610           12 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4611            8 : 
    4612            8 :                 timeline
    4613            8 :                     .metrics
    4614            8 :                     .valid_lsn_lease_count_gauge
    4615            8 :                     .set(target.leases.len() as u64);
    4616              : 
    4617              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4618            8 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4619            0 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4620            0 :                         target.within_ancestor_pitr =
    4621            0 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4622            0 :                     }
    4623            8 :                 }
    4624              : 
    4625              :                 // Update metrics that depend on GC state
    4626            8 :                 timeline
    4627            8 :                     .metrics
    4628            8 :                     .archival_size
    4629            8 :                     .set(if target.within_ancestor_pitr {
    4630            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4631              :                     } else {
    4632            8 :                         0
    4633              :                     });
    4634            8 :                 timeline.metrics.pitr_history_size.set(
    4635            8 :                     timeline
    4636            8 :                         .get_last_record_lsn()
    4637            8 :                         .checked_sub(target.cutoffs.time)
    4638            8 :                         .unwrap_or(Lsn(0))
    4639            8 :                         .0,
    4640            8 :                 );
    4641              : 
    4642              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4643              :                 // - this timeline was created while we were finding cutoffs
    4644              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4645            8 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4646            8 :                     let original_cutoffs = target.cutoffs.clone();
    4647            8 :                     // GC cutoffs should never go back
    4648            8 :                     target.cutoffs = GcCutoffs {
    4649            8 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4650            8 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4651            8 :                     }
    4652            0 :                 }
    4653              :             }
    4654              : 
    4655            8 :             gc_timelines.push(timeline);
    4656              :         }
    4657            8 :         drop(gc_cs);
    4658            8 :         Ok(gc_timelines)
    4659            8 :     }
    4660              : 
    4661              :     /// A substitute for `branch_timeline` for use in unit tests.
    4662              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4663              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4664              :     /// timeline background tasks are launched, except the flush loop.
    4665              :     #[cfg(test)]
    4666          464 :     async fn branch_timeline_test(
    4667          464 :         self: &Arc<Self>,
    4668          464 :         src_timeline: &Arc<Timeline>,
    4669          464 :         dst_id: TimelineId,
    4670          464 :         ancestor_lsn: Option<Lsn>,
    4671          464 :         ctx: &RequestContext,
    4672          464 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4673          464 :         let tl = self
    4674          464 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4675          464 :             .await?
    4676          456 :             .into_timeline_for_test();
    4677          456 :         tl.set_state(TimelineState::Active);
    4678          456 :         Ok(tl)
    4679          464 :     }
    4680              : 
    4681              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4682              :     #[cfg(test)]
    4683              :     #[allow(clippy::too_many_arguments)]
    4684           12 :     pub async fn branch_timeline_test_with_layers(
    4685           12 :         self: &Arc<Self>,
    4686           12 :         src_timeline: &Arc<Timeline>,
    4687           12 :         dst_id: TimelineId,
    4688           12 :         ancestor_lsn: Option<Lsn>,
    4689           12 :         ctx: &RequestContext,
    4690           12 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4691           12 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4692           12 :         end_lsn: Lsn,
    4693           12 :     ) -> anyhow::Result<Arc<Timeline>> {
    4694              :         use checks::check_valid_layermap;
    4695              :         use itertools::Itertools;
    4696              : 
    4697           12 :         let tline = self
    4698           12 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4699           12 :             .await?;
    4700           12 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4701           12 :             ancestor_lsn
    4702              :         } else {
    4703            0 :             tline.get_last_record_lsn()
    4704              :         };
    4705           12 :         assert!(end_lsn >= ancestor_lsn);
    4706           12 :         tline.force_advance_lsn(end_lsn);
    4707           24 :         for deltas in delta_layer_desc {
    4708           12 :             tline
    4709           12 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4710           12 :                 .await?;
    4711              :         }
    4712           20 :         for (lsn, images) in image_layer_desc {
    4713            8 :             tline
    4714            8 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4715            8 :                 .await?;
    4716              :         }
    4717           12 :         let layer_names = tline
    4718           12 :             .layers
    4719           12 :             .read()
    4720           12 :             .await
    4721           12 :             .layer_map()
    4722           12 :             .unwrap()
    4723           12 :             .iter_historic_layers()
    4724           20 :             .map(|layer| layer.layer_name())
    4725           12 :             .collect_vec();
    4726           12 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4727            0 :             bail!("invalid layermap: {err}");
    4728           12 :         }
    4729           12 :         Ok(tline)
    4730           12 :     }
    4731              : 
    4732              :     /// Branch an existing timeline.
    4733            0 :     async fn branch_timeline(
    4734            0 :         self: &Arc<Self>,
    4735            0 :         src_timeline: &Arc<Timeline>,
    4736            0 :         dst_id: TimelineId,
    4737            0 :         start_lsn: Option<Lsn>,
    4738            0 :         ctx: &RequestContext,
    4739            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4740            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4741            0 :             .await
    4742            0 :     }
    4743              : 
    4744          464 :     async fn branch_timeline_impl(
    4745          464 :         self: &Arc<Self>,
    4746          464 :         src_timeline: &Arc<Timeline>,
    4747          464 :         dst_id: TimelineId,
    4748          464 :         start_lsn: Option<Lsn>,
    4749          464 :         _ctx: &RequestContext,
    4750          464 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4751          464 :         let src_id = src_timeline.timeline_id;
    4752              : 
    4753              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4754              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4755              :         // valid while we are creating the branch.
    4756          464 :         let _gc_cs = self.gc_cs.lock().await;
    4757              : 
    4758              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4759          464 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4760            4 :             let lsn = src_timeline.get_last_record_lsn();
    4761            4 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4762            4 :             lsn
    4763          464 :         });
    4764              : 
    4765              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4766          464 :         let timeline_create_guard = match self
    4767          464 :             .start_creating_timeline(
    4768          464 :                 dst_id,
    4769          464 :                 CreateTimelineIdempotency::Branch {
    4770          464 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4771          464 :                     ancestor_start_lsn: start_lsn,
    4772          464 :                 },
    4773          464 :             )
    4774          464 :             .await?
    4775              :         {
    4776          464 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4777            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4778            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4779              :             }
    4780              :         };
    4781              : 
    4782              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4783              :         // horizon on the source timeline
    4784              :         //
    4785              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4786              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4787              :         // planned GC cutoff in 'gc_info' is normally larger than
    4788              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    4789              :         // changed the GC settings for the tenant to make the PITR window
    4790              :         // larger, but some of the data was already removed by an earlier GC
    4791              :         // iteration.
    4792              : 
    4793              :         // check against last actual 'latest_gc_cutoff' first
    4794          464 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    4795          464 :         {
    4796          464 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4797          464 :             let planned_cutoff = gc_info.min_cutoff();
    4798          464 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    4799            0 :                 tracing::info!(
    4800            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    4801            0 :                     *applied_gc_cutoff_lsn
    4802              :                 );
    4803              :             } else {
    4804          464 :                 src_timeline
    4805          464 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    4806          464 :                     .context(format!(
    4807          464 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    4808          464 :                         *applied_gc_cutoff_lsn,
    4809          464 :                     ))
    4810          464 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    4811              : 
    4812              :                 // and then the planned GC cutoff
    4813          456 :                 if start_lsn < planned_cutoff {
    4814            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4815            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    4816            0 :                     )));
    4817          456 :                 }
    4818              :             }
    4819              :         }
    4820              : 
    4821              :         //
    4822              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4823              :         // so that GC cannot advance the GC cutoff until we are finished.
    4824              :         // Proceed with the branch creation.
    4825              :         //
    4826              : 
    4827              :         // Determine prev-LSN for the new timeline. We can only determine it if
    4828              :         // the timeline was branched at the current end of the source timeline.
    4829              :         let RecordLsn {
    4830          456 :             last: src_last,
    4831          456 :             prev: src_prev,
    4832          456 :         } = src_timeline.get_last_record_rlsn();
    4833          456 :         let dst_prev = if src_last == start_lsn {
    4834          432 :             Some(src_prev)
    4835              :         } else {
    4836           24 :             None
    4837              :         };
    4838              : 
    4839              :         // Create the metadata file, noting the ancestor of the new timeline.
    4840              :         // There is initially no data in it, but all the read-calls know to look
    4841              :         // into the ancestor.
    4842          456 :         let metadata = TimelineMetadata::new(
    4843          456 :             start_lsn,
    4844          456 :             dst_prev,
    4845          456 :             Some(src_id),
    4846          456 :             start_lsn,
    4847          456 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4848          456 :             src_timeline.initdb_lsn,
    4849          456 :             src_timeline.pg_version,
    4850          456 :         );
    4851              : 
    4852          456 :         let uninitialized_timeline = self
    4853          456 :             .prepare_new_timeline(
    4854          456 :                 dst_id,
    4855          456 :                 &metadata,
    4856          456 :                 timeline_create_guard,
    4857          456 :                 start_lsn + 1,
    4858          456 :                 Some(Arc::clone(src_timeline)),
    4859          456 :             )
    4860          456 :             .await?;
    4861              : 
    4862          456 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    4863              : 
    4864              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4865              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4866              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4867              :         // could get incorrect information and remove more layers, than needed.
    4868              :         // See also https://github.com/neondatabase/neon/issues/3865
    4869          456 :         new_timeline
    4870          456 :             .remote_client
    4871          456 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4872          456 :             .context("branch initial metadata upload")?;
    4873              : 
    4874              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4875              : 
    4876          456 :         Ok(CreateTimelineResult::Created(new_timeline))
    4877          464 :     }
    4878              : 
    4879              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4880              :     #[cfg(test)]
    4881              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4882              :     pub(crate) async fn bootstrap_timeline_test(
    4883              :         self: &Arc<Self>,
    4884              :         timeline_id: TimelineId,
    4885              :         pg_version: u32,
    4886              :         load_existing_initdb: Option<TimelineId>,
    4887              :         ctx: &RequestContext,
    4888              :     ) -> anyhow::Result<Arc<Timeline>> {
    4889              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4890              :             .await
    4891              :             .map_err(anyhow::Error::new)
    4892            4 :             .map(|r| r.into_timeline_for_test())
    4893              :     }
    4894              : 
    4895              :     /// Get exclusive access to the timeline ID for creation.
    4896              :     ///
    4897              :     /// Timeline-creating code paths must use this function before making changes
    4898              :     /// to in-memory or persistent state.
    4899              :     ///
    4900              :     /// The `state` parameter is a description of the timeline creation operation
    4901              :     /// we intend to perform.
    4902              :     /// If the timeline was already created in the meantime, we check whether this
    4903              :     /// request conflicts or is idempotent , based on `state`.
    4904          896 :     async fn start_creating_timeline(
    4905          896 :         self: &Arc<Self>,
    4906          896 :         new_timeline_id: TimelineId,
    4907          896 :         idempotency: CreateTimelineIdempotency,
    4908          896 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4909          896 :         let allow_offloaded = false;
    4910          896 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4911          892 :             Ok(create_guard) => {
    4912          892 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4913          892 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4914              :             }
    4915            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4916              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4917              :                 // Creation is in progress, we cannot create it again, and we cannot
    4918              :                 // check if this request matches the existing one, so caller must try
    4919              :                 // again later.
    4920            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4921              :             }
    4922            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4923              :             Err(TimelineExclusionError::AlreadyExists {
    4924            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    4925            0 :                 ..
    4926            0 :             }) => {
    4927            0 :                 info!("timeline already exists but is offloaded");
    4928            0 :                 Err(CreateTimelineError::Conflict)
    4929              :             }
    4930              :             Err(TimelineExclusionError::AlreadyExists {
    4931            4 :                 existing: TimelineOrOffloaded::Timeline(existing),
    4932            4 :                 arg,
    4933            4 :             }) => {
    4934            4 :                 {
    4935            4 :                     let existing = &existing.create_idempotency;
    4936            4 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    4937            4 :                     debug!("timeline already exists");
    4938              : 
    4939            4 :                     match (existing, &arg) {
    4940              :                         // FailWithConflict => no idempotency check
    4941              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    4942              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    4943            4 :                             warn!("timeline already exists, failing request");
    4944            4 :                             return Err(CreateTimelineError::Conflict);
    4945              :                         }
    4946              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    4947            0 :                         (x, y) if x == y => {
    4948            0 :                             info!(
    4949            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    4950              :                             );
    4951              :                             // fallthrough
    4952              :                         }
    4953              :                         (_, _) => {
    4954            0 :                             warn!("idempotency conflict, failing request");
    4955            0 :                             return Err(CreateTimelineError::Conflict);
    4956              :                         }
    4957              :                     }
    4958              :                 }
    4959              : 
    4960            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    4961              :             }
    4962              :         }
    4963          896 :     }
    4964              : 
    4965            0 :     async fn upload_initdb(
    4966            0 :         &self,
    4967            0 :         timelines_path: &Utf8PathBuf,
    4968            0 :         pgdata_path: &Utf8PathBuf,
    4969            0 :         timeline_id: &TimelineId,
    4970            0 :     ) -> anyhow::Result<()> {
    4971            0 :         let temp_path = timelines_path.join(format!(
    4972            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    4973            0 :         ));
    4974            0 : 
    4975            0 :         scopeguard::defer! {
    4976            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    4977            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    4978            0 :             }
    4979            0 :         }
    4980              : 
    4981            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    4982              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    4983            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    4984            0 :             warn!(
    4985            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    4986              :             );
    4987            0 :         }
    4988              : 
    4989            0 :         pausable_failpoint!("before-initdb-upload");
    4990              : 
    4991            0 :         backoff::retry(
    4992            0 :             || async {
    4993            0 :                 self::remote_timeline_client::upload_initdb_dir(
    4994            0 :                     &self.remote_storage,
    4995            0 :                     &self.tenant_shard_id.tenant_id,
    4996            0 :                     timeline_id,
    4997            0 :                     pgdata_zstd.try_clone().await?,
    4998            0 :                     tar_zst_size,
    4999            0 :                     &self.cancel,
    5000            0 :                 )
    5001            0 :                 .await
    5002            0 :             },
    5003            0 :             |_| false,
    5004            0 :             3,
    5005            0 :             u32::MAX,
    5006            0 :             "persist_initdb_tar_zst",
    5007            0 :             &self.cancel,
    5008            0 :         )
    5009            0 :         .await
    5010            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5011            0 :         .and_then(|x| x)
    5012            0 :     }
    5013              : 
    5014              :     /// - run initdb to init temporary instance and get bootstrap data
    5015              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5016            4 :     async fn bootstrap_timeline(
    5017            4 :         self: &Arc<Self>,
    5018            4 :         timeline_id: TimelineId,
    5019            4 :         pg_version: u32,
    5020            4 :         load_existing_initdb: Option<TimelineId>,
    5021            4 :         ctx: &RequestContext,
    5022            4 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5023            4 :         let timeline_create_guard = match self
    5024            4 :             .start_creating_timeline(
    5025            4 :                 timeline_id,
    5026            4 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5027            4 :             )
    5028            4 :             .await?
    5029              :         {
    5030            4 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5031            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5032            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5033              :             }
    5034              :         };
    5035              : 
    5036              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5037              :         // temporary directory for basebackup files for the given timeline.
    5038              : 
    5039            4 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5040            4 :         let pgdata_path = path_with_suffix_extension(
    5041            4 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5042            4 :             TEMP_FILE_SUFFIX,
    5043            4 :         );
    5044            4 : 
    5045            4 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5046            4 :         // we won't race with other creations or existent timelines with the same path.
    5047            4 :         if pgdata_path.exists() {
    5048            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5049            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5050            0 :             })?;
    5051            4 :         }
    5052              : 
    5053              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5054            4 :         let pgdata_path_deferred = pgdata_path.clone();
    5055            4 :         scopeguard::defer! {
    5056            4 :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred) {
    5057            4 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5058            4 :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5059            4 :             }
    5060            4 :         }
    5061            4 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5062            4 :             if existing_initdb_timeline_id != timeline_id {
    5063            0 :                 let source_path = &remote_initdb_archive_path(
    5064            0 :                     &self.tenant_shard_id.tenant_id,
    5065            0 :                     &existing_initdb_timeline_id,
    5066            0 :                 );
    5067            0 :                 let dest_path =
    5068            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5069            0 : 
    5070            0 :                 // if this fails, it will get retried by retried control plane requests
    5071            0 :                 self.remote_storage
    5072            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5073            0 :                     .await
    5074            0 :                     .context("copy initdb tar")?;
    5075            4 :             }
    5076            4 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5077            4 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5078            4 :                     self.conf,
    5079            4 :                     &self.remote_storage,
    5080            4 :                     &self.tenant_shard_id,
    5081            4 :                     &existing_initdb_timeline_id,
    5082            4 :                     &self.cancel,
    5083            4 :                 )
    5084            4 :                 .await
    5085            4 :                 .context("download initdb tar")?;
    5086              : 
    5087            4 :             scopeguard::defer! {
    5088            4 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5089            4 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5090            4 :                 }
    5091            4 :             }
    5092            4 : 
    5093            4 :             let buf_read =
    5094            4 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5095            4 :             extract_zst_tarball(&pgdata_path, buf_read)
    5096            4 :                 .await
    5097            4 :                 .context("extract initdb tar")?;
    5098              :         } else {
    5099              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5100            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5101            0 :                 .await
    5102            0 :                 .context("run initdb")?;
    5103              : 
    5104              :             // Upload the created data dir to S3
    5105            0 :             if self.tenant_shard_id().is_shard_zero() {
    5106            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5107            0 :                     .await?;
    5108            0 :             }
    5109              :         }
    5110            4 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5111            4 : 
    5112            4 :         // Import the contents of the data directory at the initial checkpoint
    5113            4 :         // LSN, and any WAL after that.
    5114            4 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5115            4 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5116            4 :         let new_metadata = TimelineMetadata::new(
    5117            4 :             Lsn(0),
    5118            4 :             None,
    5119            4 :             None,
    5120            4 :             Lsn(0),
    5121            4 :             pgdata_lsn,
    5122            4 :             pgdata_lsn,
    5123            4 :             pg_version,
    5124            4 :         );
    5125            4 :         let mut raw_timeline = self
    5126            4 :             .prepare_new_timeline(
    5127            4 :                 timeline_id,
    5128            4 :                 &new_metadata,
    5129            4 :                 timeline_create_guard,
    5130            4 :                 pgdata_lsn,
    5131            4 :                 None,
    5132            4 :             )
    5133            4 :             .await?;
    5134              : 
    5135            4 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5136            4 :         raw_timeline
    5137            4 :             .write(|unfinished_timeline| async move {
    5138            4 :                 import_datadir::import_timeline_from_postgres_datadir(
    5139            4 :                     &unfinished_timeline,
    5140            4 :                     &pgdata_path,
    5141            4 :                     pgdata_lsn,
    5142            4 :                     ctx,
    5143            4 :                 )
    5144            4 :                 .await
    5145            4 :                 .with_context(|| {
    5146            0 :                     format!(
    5147            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5148            0 :                     )
    5149            4 :                 })?;
    5150              : 
    5151            4 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5152            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5153            0 :                         "failpoint before-checkpoint-new-timeline"
    5154            0 :                     )))
    5155            4 :                 });
    5156              : 
    5157            4 :                 Ok(())
    5158            8 :             })
    5159            4 :             .await?;
    5160              : 
    5161              :         // All done!
    5162            4 :         let timeline = raw_timeline.finish_creation().await?;
    5163              : 
    5164              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5165              : 
    5166            4 :         Ok(CreateTimelineResult::Created(timeline))
    5167            4 :     }
    5168              : 
    5169          884 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5170          884 :         RemoteTimelineClient::new(
    5171          884 :             self.remote_storage.clone(),
    5172          884 :             self.deletion_queue_client.clone(),
    5173          884 :             self.conf,
    5174          884 :             self.tenant_shard_id,
    5175          884 :             timeline_id,
    5176          884 :             self.generation,
    5177          884 :             &self.tenant_conf.load().location,
    5178          884 :         )
    5179          884 :     }
    5180              : 
    5181              :     /// Builds required resources for a new timeline.
    5182          884 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5183          884 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5184          884 :         self.get_timeline_resources_for(remote_client)
    5185          884 :     }
    5186              : 
    5187              :     /// Builds timeline resources for the given remote client.
    5188          896 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5189          896 :         TimelineResources {
    5190          896 :             remote_client,
    5191          896 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5192          896 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5193          896 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5194          896 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5195          896 :         }
    5196          896 :     }
    5197              : 
    5198              :     /// Creates intermediate timeline structure and its files.
    5199              :     ///
    5200              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5201              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5202              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5203          884 :     async fn prepare_new_timeline<'a>(
    5204          884 :         &'a self,
    5205          884 :         new_timeline_id: TimelineId,
    5206          884 :         new_metadata: &TimelineMetadata,
    5207          884 :         create_guard: TimelineCreateGuard,
    5208          884 :         start_lsn: Lsn,
    5209          884 :         ancestor: Option<Arc<Timeline>>,
    5210          884 :     ) -> anyhow::Result<UninitializedTimeline<'a>> {
    5211          884 :         let tenant_shard_id = self.tenant_shard_id;
    5212          884 : 
    5213          884 :         let resources = self.build_timeline_resources(new_timeline_id);
    5214          884 :         resources
    5215          884 :             .remote_client
    5216          884 :             .init_upload_queue_for_empty_remote(new_metadata)?;
    5217              : 
    5218          884 :         let timeline_struct = self
    5219          884 :             .create_timeline_struct(
    5220          884 :                 new_timeline_id,
    5221          884 :                 new_metadata,
    5222          884 :                 None,
    5223          884 :                 ancestor,
    5224          884 :                 resources,
    5225          884 :                 CreateTimelineCause::Load,
    5226          884 :                 create_guard.idempotency.clone(),
    5227          884 :                 None,
    5228          884 :             )
    5229          884 :             .context("Failed to create timeline data structure")?;
    5230              : 
    5231          884 :         timeline_struct.init_empty_layer_map(start_lsn);
    5232              : 
    5233          884 :         if let Err(e) = self
    5234          884 :             .create_timeline_files(&create_guard.timeline_path)
    5235          884 :             .await
    5236              :         {
    5237            0 :             error!(
    5238            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5239              :             );
    5240            0 :             cleanup_timeline_directory(create_guard);
    5241            0 :             return Err(e);
    5242          884 :         }
    5243          884 : 
    5244          884 :         debug!(
    5245            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5246              :         );
    5247              : 
    5248          884 :         Ok(UninitializedTimeline::new(
    5249          884 :             self,
    5250          884 :             new_timeline_id,
    5251          884 :             Some((timeline_struct, create_guard)),
    5252          884 :         ))
    5253          884 :     }
    5254              : 
    5255          884 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5256          884 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5257              : 
    5258          884 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5259            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5260          884 :         });
    5261              : 
    5262          884 :         Ok(())
    5263          884 :     }
    5264              : 
    5265              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5266              :     /// concurrent attempts to create the same timeline.
    5267              :     ///
    5268              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5269              :     /// offloaded timelines or not.
    5270          896 :     fn create_timeline_create_guard(
    5271          896 :         self: &Arc<Self>,
    5272          896 :         timeline_id: TimelineId,
    5273          896 :         idempotency: CreateTimelineIdempotency,
    5274          896 :         allow_offloaded: bool,
    5275          896 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5276          896 :         let tenant_shard_id = self.tenant_shard_id;
    5277          896 : 
    5278          896 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5279              : 
    5280          896 :         let create_guard = TimelineCreateGuard::new(
    5281          896 :             self,
    5282          896 :             timeline_id,
    5283          896 :             timeline_path.clone(),
    5284          896 :             idempotency,
    5285          896 :             allow_offloaded,
    5286          896 :         )?;
    5287              : 
    5288              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5289              :         // for creation.
    5290              :         // A timeline directory should never exist on disk already:
    5291              :         // - a previous failed creation would have cleaned up after itself
    5292              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5293              :         //
    5294              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5295              :         // this error may indicate a bug in cleanup on failed creations.
    5296          892 :         if timeline_path.exists() {
    5297            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5298            0 :                 "Timeline directory already exists! This is a bug."
    5299            0 :             )));
    5300          892 :         }
    5301          892 : 
    5302          892 :         Ok(create_guard)
    5303          896 :     }
    5304              : 
    5305              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5306              :     ///
    5307              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5308              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5309              :     pub async fn gather_size_inputs(
    5310              :         &self,
    5311              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5312              :         // (only if it is shorter than the real cutoff).
    5313              :         max_retention_period: Option<u64>,
    5314              :         cause: LogicalSizeCalculationCause,
    5315              :         cancel: &CancellationToken,
    5316              :         ctx: &RequestContext,
    5317              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5318              :         let logical_sizes_at_once = self
    5319              :             .conf
    5320              :             .concurrent_tenant_size_logical_size_queries
    5321              :             .inner();
    5322              : 
    5323              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5324              :         //
    5325              :         // But the only case where we need to run multiple of these at once is when we
    5326              :         // request a size for a tenant manually via API, while another background calculation
    5327              :         // is in progress (which is not a common case).
    5328              :         //
    5329              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5330              :         let mut shared_cache = tokio::select! {
    5331              :             locked = self.cached_logical_sizes.lock() => locked,
    5332              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5333              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5334              :         };
    5335              : 
    5336              :         size::gather_inputs(
    5337              :             self,
    5338              :             logical_sizes_at_once,
    5339              :             max_retention_period,
    5340              :             &mut shared_cache,
    5341              :             cause,
    5342              :             cancel,
    5343              :             ctx,
    5344              :         )
    5345              :         .await
    5346              :     }
    5347              : 
    5348              :     /// Calculate synthetic tenant size and cache the result.
    5349              :     /// This is periodically called by background worker.
    5350              :     /// result is cached in tenant struct
    5351              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5352              :     pub async fn calculate_synthetic_size(
    5353              :         &self,
    5354              :         cause: LogicalSizeCalculationCause,
    5355              :         cancel: &CancellationToken,
    5356              :         ctx: &RequestContext,
    5357              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5358              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5359              : 
    5360              :         let size = inputs.calculate();
    5361              : 
    5362              :         self.set_cached_synthetic_size(size);
    5363              : 
    5364              :         Ok(size)
    5365              :     }
    5366              : 
    5367              :     /// Cache given synthetic size and update the metric value
    5368            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5369            0 :         self.cached_synthetic_tenant_size
    5370            0 :             .store(size, Ordering::Relaxed);
    5371            0 : 
    5372            0 :         // Only shard zero should be calculating synthetic sizes
    5373            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5374              : 
    5375            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5376            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5377            0 :             .unwrap()
    5378            0 :             .set(size);
    5379            0 :     }
    5380              : 
    5381            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5382            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5383            0 :     }
    5384              : 
    5385              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5386              :     ///
    5387              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5388              :     /// from an external API handler.
    5389              :     ///
    5390              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5391              :     /// still bounded by tenant/timeline shutdown.
    5392              :     #[tracing::instrument(skip_all)]
    5393              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5394              :         let timelines = self.timelines.lock().unwrap().clone();
    5395              : 
    5396            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5397            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5398            0 :             timeline.freeze_and_flush().await?;
    5399            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5400            0 :             timeline.remote_client.wait_completion().await?;
    5401              : 
    5402            0 :             Ok(())
    5403            0 :         }
    5404              : 
    5405              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5406              :         // aborted when this function's future is cancelled: they should stay alive
    5407              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5408              :         // before Timeline shutdown completes.
    5409              :         let mut results = FuturesUnordered::new();
    5410              : 
    5411              :         for (_timeline_id, timeline) in timelines {
    5412              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5413              :             // means that if this function's future is cancelled, the Timeline shutdown
    5414              :             // will still wait for any I/O in here to complete.
    5415              :             let Ok(gate) = timeline.gate.enter() else {
    5416              :                 continue;
    5417              :             };
    5418            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5419              :             results.push(jh);
    5420              :         }
    5421              : 
    5422              :         while let Some(r) = results.next().await {
    5423              :             if let Err(e) = r {
    5424              :                 if !e.is_cancelled() && !e.is_panic() {
    5425              :                     tracing::error!("unexpected join error: {e:?}");
    5426              :                 }
    5427              :             }
    5428              :         }
    5429              : 
    5430              :         // The flushes we did above were just writes, but the Tenant might have had
    5431              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5432              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5433              :         // because it's typically a no-op.
    5434              :         match self.deletion_queue_client.flush_execute().await {
    5435              :             Ok(_) => {}
    5436              :             Err(DeletionQueueError::ShuttingDown) => {}
    5437              :         }
    5438              : 
    5439              :         Ok(())
    5440              :     }
    5441              : 
    5442            0 :     pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
    5443            0 :         self.tenant_conf.load().tenant_conf.clone()
    5444            0 :     }
    5445              : 
    5446              :     /// How much local storage would this tenant like to have?  It can cope with
    5447              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5448              :     /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
    5449              :     /// by keeping important things on local disk.
    5450              :     ///
    5451              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5452              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5453              :     /// actually use more than they report here.
    5454            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5455            0 :         let timelines = self.timelines.lock().unwrap();
    5456            0 : 
    5457            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5458            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5459            0 :         // of them is used actively enough to occupy space on disk.
    5460            0 :         timelines
    5461            0 :             .values()
    5462            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5463            0 :             .max()
    5464            0 :             .unwrap_or(0)
    5465            0 :     }
    5466              : 
    5467              :     /// Serialize and write the latest TenantManifest to remote storage.
    5468            4 :     pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5469              :         // Only one manifest write may be done at at time, and the contents of the manifest
    5470              :         // must be loaded while holding this lock. This makes it safe to call this function
    5471              :         // from anywhere without worrying about colliding updates.
    5472            4 :         let mut guard = tokio::select! {
    5473            4 :             g = self.tenant_manifest_upload.lock() => {
    5474            4 :                 g
    5475              :             },
    5476            4 :             _ = self.cancel.cancelled() => {
    5477            0 :                 return Err(TenantManifestError::Cancelled);
    5478              :             }
    5479              :         };
    5480              : 
    5481            4 :         let manifest = self.build_tenant_manifest();
    5482            4 :         if Some(&manifest) == (*guard).as_ref() {
    5483              :             // Optimisation: skip uploads that don't change anything.
    5484            0 :             return Ok(());
    5485            4 :         }
    5486            4 : 
    5487            4 :         // Remote storage does no retries internally, so wrap it
    5488            4 :         match backoff::retry(
    5489            4 :             || async {
    5490            4 :                 upload_tenant_manifest(
    5491            4 :                     &self.remote_storage,
    5492            4 :                     &self.tenant_shard_id,
    5493            4 :                     self.generation,
    5494            4 :                     &manifest,
    5495            4 :                     &self.cancel,
    5496            4 :                 )
    5497            4 :                 .await
    5498            8 :             },
    5499            4 :             |_e| self.cancel.is_cancelled(),
    5500            4 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5501            4 :             FAILED_REMOTE_OP_RETRIES,
    5502            4 :             "uploading tenant manifest",
    5503            4 :             &self.cancel,
    5504            4 :         )
    5505            4 :         .await
    5506              :         {
    5507            0 :             None => Err(TenantManifestError::Cancelled),
    5508            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5509            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5510              :             Some(Ok(_)) => {
    5511              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5512              :                 // re-uploading the same thing.
    5513            4 :                 *guard = Some(manifest);
    5514            4 : 
    5515            4 :                 Ok(())
    5516              :             }
    5517              :         }
    5518            4 :     }
    5519              : }
    5520              : 
    5521              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5522              : /// to get bootstrap data for timeline initialization.
    5523            0 : async fn run_initdb(
    5524            0 :     conf: &'static PageServerConf,
    5525            0 :     initdb_target_dir: &Utf8Path,
    5526            0 :     pg_version: u32,
    5527            0 :     cancel: &CancellationToken,
    5528            0 : ) -> Result<(), InitdbError> {
    5529            0 :     let initdb_bin_path = conf
    5530            0 :         .pg_bin_dir(pg_version)
    5531            0 :         .map_err(InitdbError::Other)?
    5532            0 :         .join("initdb");
    5533            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5534            0 :     info!(
    5535            0 :         "running {} in {}, libdir: {}",
    5536              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5537              :     );
    5538              : 
    5539            0 :     let _permit = {
    5540            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5541            0 :         INIT_DB_SEMAPHORE.acquire().await
    5542              :     };
    5543              : 
    5544            0 :     CONCURRENT_INITDBS.inc();
    5545            0 :     scopeguard::defer! {
    5546            0 :         CONCURRENT_INITDBS.dec();
    5547            0 :     }
    5548            0 : 
    5549            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5550            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5551            0 :         superuser: &conf.superuser,
    5552            0 :         locale: &conf.locale,
    5553            0 :         initdb_bin: &initdb_bin_path,
    5554            0 :         pg_version,
    5555            0 :         library_search_path: &initdb_lib_dir,
    5556            0 :         pgdata: initdb_target_dir,
    5557            0 :     })
    5558            0 :     .await
    5559            0 :     .map_err(InitdbError::Inner);
    5560            0 : 
    5561            0 :     // This isn't true cancellation support, see above. Still return an error to
    5562            0 :     // excercise the cancellation code path.
    5563            0 :     if cancel.is_cancelled() {
    5564            0 :         return Err(InitdbError::Cancelled);
    5565            0 :     }
    5566            0 : 
    5567            0 :     res
    5568            0 : }
    5569              : 
    5570              : /// Dump contents of a layer file to stdout.
    5571            0 : pub async fn dump_layerfile_from_path(
    5572            0 :     path: &Utf8Path,
    5573            0 :     verbose: bool,
    5574            0 :     ctx: &RequestContext,
    5575            0 : ) -> anyhow::Result<()> {
    5576              :     use std::os::unix::fs::FileExt;
    5577              : 
    5578              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5579              :     // file.
    5580            0 :     let file = File::open(path)?;
    5581            0 :     let mut header_buf = [0u8; 2];
    5582            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5583              : 
    5584            0 :     match u16::from_be_bytes(header_buf) {
    5585              :         crate::IMAGE_FILE_MAGIC => {
    5586            0 :             ImageLayer::new_for_path(path, file)?
    5587            0 :                 .dump(verbose, ctx)
    5588            0 :                 .await?
    5589              :         }
    5590              :         crate::DELTA_FILE_MAGIC => {
    5591            0 :             DeltaLayer::new_for_path(path, file)?
    5592            0 :                 .dump(verbose, ctx)
    5593            0 :                 .await?
    5594              :         }
    5595            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5596              :     }
    5597              : 
    5598            0 :     Ok(())
    5599            0 : }
    5600              : 
    5601              : #[cfg(test)]
    5602              : pub(crate) mod harness {
    5603              :     use bytes::{Bytes, BytesMut};
    5604              :     use hex_literal::hex;
    5605              :     use once_cell::sync::OnceCell;
    5606              :     use pageserver_api::key::Key;
    5607              :     use pageserver_api::models::ShardParameters;
    5608              :     use pageserver_api::record::NeonWalRecord;
    5609              :     use pageserver_api::shard::ShardIndex;
    5610              :     use utils::id::TenantId;
    5611              :     use utils::logging;
    5612              : 
    5613              :     use super::*;
    5614              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5615              :     use crate::l0_flush::L0FlushConfig;
    5616              :     use crate::walredo::apply_neon;
    5617              : 
    5618              :     pub const TIMELINE_ID: TimelineId =
    5619              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5620              :     pub const NEW_TIMELINE_ID: TimelineId =
    5621              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5622              : 
    5623              :     /// Convenience function to create a page image with given string as the only content
    5624     10057572 :     pub fn test_img(s: &str) -> Bytes {
    5625     10057572 :         let mut buf = BytesMut::new();
    5626     10057572 :         buf.extend_from_slice(s.as_bytes());
    5627     10057572 :         buf.resize(64, 0);
    5628     10057572 : 
    5629     10057572 :         buf.freeze()
    5630     10057572 :     }
    5631              : 
    5632              :     impl From<TenantConf> for TenantConfOpt {
    5633          444 :         fn from(tenant_conf: TenantConf) -> Self {
    5634          444 :             Self {
    5635          444 :                 checkpoint_distance: Some(tenant_conf.checkpoint_distance),
    5636          444 :                 checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
    5637          444 :                 compaction_target_size: Some(tenant_conf.compaction_target_size),
    5638          444 :                 compaction_period: Some(tenant_conf.compaction_period),
    5639          444 :                 compaction_threshold: Some(tenant_conf.compaction_threshold),
    5640          444 :                 compaction_upper_limit: Some(tenant_conf.compaction_upper_limit),
    5641          444 :                 compaction_algorithm: Some(tenant_conf.compaction_algorithm),
    5642          444 :                 compaction_l0_first: Some(tenant_conf.compaction_l0_first),
    5643          444 :                 compaction_l0_semaphore: Some(tenant_conf.compaction_l0_semaphore),
    5644          444 :                 l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
    5645          444 :                 l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
    5646          444 :                 l0_flush_wait_upload: Some(tenant_conf.l0_flush_wait_upload),
    5647          444 :                 gc_horizon: Some(tenant_conf.gc_horizon),
    5648          444 :                 gc_period: Some(tenant_conf.gc_period),
    5649          444 :                 image_creation_threshold: Some(tenant_conf.image_creation_threshold),
    5650          444 :                 pitr_interval: Some(tenant_conf.pitr_interval),
    5651          444 :                 walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
    5652          444 :                 lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
    5653          444 :                 max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
    5654          444 :                 eviction_policy: Some(tenant_conf.eviction_policy),
    5655          444 :                 min_resident_size_override: tenant_conf.min_resident_size_override,
    5656          444 :                 evictions_low_residence_duration_metric_threshold: Some(
    5657          444 :                     tenant_conf.evictions_low_residence_duration_metric_threshold,
    5658          444 :                 ),
    5659          444 :                 heatmap_period: Some(tenant_conf.heatmap_period),
    5660          444 :                 lazy_slru_download: Some(tenant_conf.lazy_slru_download),
    5661          444 :                 timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
    5662          444 :                 image_layer_creation_check_threshold: Some(
    5663          444 :                     tenant_conf.image_layer_creation_check_threshold,
    5664          444 :                 ),
    5665          444 :                 image_creation_preempt_threshold: Some(
    5666          444 :                     tenant_conf.image_creation_preempt_threshold,
    5667          444 :                 ),
    5668          444 :                 lsn_lease_length: Some(tenant_conf.lsn_lease_length),
    5669          444 :                 lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
    5670          444 :                 timeline_offloading: Some(tenant_conf.timeline_offloading),
    5671          444 :                 wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
    5672          444 :                 rel_size_v2_enabled: Some(tenant_conf.rel_size_v2_enabled),
    5673          444 :                 gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
    5674          444 :                 gc_compaction_initial_threshold_kb: Some(
    5675          444 :                     tenant_conf.gc_compaction_initial_threshold_kb,
    5676          444 :                 ),
    5677          444 :                 gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
    5678          444 :             }
    5679          444 :         }
    5680              :     }
    5681              : 
    5682              :     pub struct TenantHarness {
    5683              :         pub conf: &'static PageServerConf,
    5684              :         pub tenant_conf: TenantConf,
    5685              :         pub tenant_shard_id: TenantShardId,
    5686              :         pub generation: Generation,
    5687              :         pub shard: ShardIndex,
    5688              :         pub remote_storage: GenericRemoteStorage,
    5689              :         pub remote_fs_dir: Utf8PathBuf,
    5690              :         pub deletion_queue: MockDeletionQueue,
    5691              :     }
    5692              : 
    5693              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5694              : 
    5695          492 :     pub(crate) fn setup_logging() {
    5696          492 :         LOG_HANDLE.get_or_init(|| {
    5697          468 :             logging::init(
    5698          468 :                 logging::LogFormat::Test,
    5699          468 :                 // enable it in case the tests exercise code paths that use
    5700          468 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5701          468 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5702          468 :                 logging::Output::Stdout,
    5703          468 :             )
    5704          468 :             .expect("Failed to init test logging")
    5705          492 :         });
    5706          492 :     }
    5707              : 
    5708              :     impl TenantHarness {
    5709          444 :         pub async fn create_custom(
    5710          444 :             test_name: &'static str,
    5711          444 :             tenant_conf: TenantConf,
    5712          444 :             tenant_id: TenantId,
    5713          444 :             shard_identity: ShardIdentity,
    5714          444 :             generation: Generation,
    5715          444 :         ) -> anyhow::Result<Self> {
    5716          444 :             setup_logging();
    5717          444 : 
    5718          444 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5719          444 :             let _ = fs::remove_dir_all(&repo_dir);
    5720          444 :             fs::create_dir_all(&repo_dir)?;
    5721              : 
    5722          444 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5723          444 :             // Make a static copy of the config. This can never be free'd, but that's
    5724          444 :             // OK in a test.
    5725          444 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5726          444 : 
    5727          444 :             let shard = shard_identity.shard_index();
    5728          444 :             let tenant_shard_id = TenantShardId {
    5729          444 :                 tenant_id,
    5730          444 :                 shard_number: shard.shard_number,
    5731          444 :                 shard_count: shard.shard_count,
    5732          444 :             };
    5733          444 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5734          444 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5735              : 
    5736              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5737          444 :             let remote_fs_dir = conf.workdir.join("localfs");
    5738          444 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5739          444 :             let config = RemoteStorageConfig {
    5740          444 :                 storage: RemoteStorageKind::LocalFs {
    5741          444 :                     local_path: remote_fs_dir.clone(),
    5742          444 :                 },
    5743          444 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5744          444 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5745          444 :             };
    5746          444 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5747          444 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5748          444 : 
    5749          444 :             Ok(Self {
    5750          444 :                 conf,
    5751          444 :                 tenant_conf,
    5752          444 :                 tenant_shard_id,
    5753          444 :                 generation,
    5754          444 :                 shard,
    5755          444 :                 remote_storage,
    5756          444 :                 remote_fs_dir,
    5757          444 :                 deletion_queue,
    5758          444 :             })
    5759          444 :         }
    5760              : 
    5761          420 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5762          420 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5763          420 :             // The tests perform them manually if needed.
    5764          420 :             let tenant_conf = TenantConf {
    5765          420 :                 gc_period: Duration::ZERO,
    5766          420 :                 compaction_period: Duration::ZERO,
    5767          420 :                 ..TenantConf::default()
    5768          420 :             };
    5769          420 :             let tenant_id = TenantId::generate();
    5770          420 :             let shard = ShardIdentity::unsharded();
    5771          420 :             Self::create_custom(
    5772          420 :                 test_name,
    5773          420 :                 tenant_conf,
    5774          420 :                 tenant_id,
    5775          420 :                 shard,
    5776          420 :                 Generation::new(0xdeadbeef),
    5777          420 :             )
    5778          420 :             .await
    5779          420 :         }
    5780              : 
    5781           40 :         pub fn span(&self) -> tracing::Span {
    5782           40 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5783           40 :         }
    5784              : 
    5785          444 :         pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
    5786          444 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    5787          444 :             (
    5788          444 :                 self.do_try_load(&ctx)
    5789          444 :                     .await
    5790          444 :                     .expect("failed to load test tenant"),
    5791          444 :                 ctx,
    5792          444 :             )
    5793          444 :         }
    5794              : 
    5795              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5796              :         pub(crate) async fn do_try_load(
    5797              :             &self,
    5798              :             ctx: &RequestContext,
    5799              :         ) -> anyhow::Result<Arc<Tenant>> {
    5800              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5801              : 
    5802              :             let tenant = Arc::new(Tenant::new(
    5803              :                 TenantState::Attaching,
    5804              :                 self.conf,
    5805              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5806              :                     TenantConfOpt::from(self.tenant_conf.clone()),
    5807              :                     self.generation,
    5808              :                     &ShardParameters::default(),
    5809              :                 ))
    5810              :                 .unwrap(),
    5811              :                 // This is a legacy/test code path: sharding isn't supported here.
    5812              :                 ShardIdentity::unsharded(),
    5813              :                 Some(walredo_mgr),
    5814              :                 self.tenant_shard_id,
    5815              :                 self.remote_storage.clone(),
    5816              :                 self.deletion_queue.new_client(),
    5817              :                 // TODO: ideally we should run all unit tests with both configs
    5818              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5819              :             ));
    5820              : 
    5821              :             let preload = tenant
    5822              :                 .preload(&self.remote_storage, CancellationToken::new())
    5823              :                 .await?;
    5824              :             tenant.attach(Some(preload), ctx).await?;
    5825              : 
    5826              :             tenant.state.send_replace(TenantState::Active);
    5827              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5828              :                 timeline.set_state(TimelineState::Active);
    5829              :             }
    5830              :             Ok(tenant)
    5831              :         }
    5832              : 
    5833            4 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5834            4 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5835            4 :         }
    5836              :     }
    5837              : 
    5838              :     // Mock WAL redo manager that doesn't do much
    5839              :     pub(crate) struct TestRedoManager;
    5840              : 
    5841              :     impl TestRedoManager {
    5842              :         /// # Cancel-Safety
    5843              :         ///
    5844              :         /// This method is cancellation-safe.
    5845         1636 :         pub async fn request_redo(
    5846         1636 :             &self,
    5847         1636 :             key: Key,
    5848         1636 :             lsn: Lsn,
    5849         1636 :             base_img: Option<(Lsn, Bytes)>,
    5850         1636 :             records: Vec<(Lsn, NeonWalRecord)>,
    5851         1636 :             _pg_version: u32,
    5852         1636 :         ) -> Result<Bytes, walredo::Error> {
    5853         2392 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5854         1636 :             if records_neon {
    5855              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5856         1636 :                 let mut page = match (base_img, records.first()) {
    5857         1504 :                     (Some((_lsn, img)), _) => {
    5858         1504 :                         let mut page = BytesMut::new();
    5859         1504 :                         page.extend_from_slice(&img);
    5860         1504 :                         page
    5861              :                     }
    5862          132 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5863              :                     _ => {
    5864            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5865              :                     }
    5866              :                 };
    5867              : 
    5868         4028 :                 for (record_lsn, record) in records {
    5869         2392 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5870              :                 }
    5871         1636 :                 Ok(page.freeze())
    5872              :             } else {
    5873              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5874            0 :                 let s = format!(
    5875            0 :                     "redo for {} to get to {}, with {} and {} records",
    5876            0 :                     key,
    5877            0 :                     lsn,
    5878            0 :                     if base_img.is_some() {
    5879            0 :                         "base image"
    5880              :                     } else {
    5881            0 :                         "no base image"
    5882              :                     },
    5883            0 :                     records.len()
    5884            0 :                 );
    5885            0 :                 println!("{s}");
    5886            0 : 
    5887            0 :                 Ok(test_img(&s))
    5888              :             }
    5889         1636 :         }
    5890              :     }
    5891              : }
    5892              : 
    5893              : #[cfg(test)]
    5894              : mod tests {
    5895              :     use std::collections::{BTreeMap, BTreeSet};
    5896              : 
    5897              :     use bytes::{Bytes, BytesMut};
    5898              :     use hex_literal::hex;
    5899              :     use itertools::Itertools;
    5900              :     #[cfg(feature = "testing")]
    5901              :     use models::CompactLsnRange;
    5902              :     use pageserver_api::key::{AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
    5903              :     use pageserver_api::keyspace::KeySpace;
    5904              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5905              :     #[cfg(feature = "testing")]
    5906              :     use pageserver_api::record::NeonWalRecord;
    5907              :     use pageserver_api::value::Value;
    5908              :     use pageserver_compaction::helpers::overlaps_with;
    5909              :     use rand::{Rng, thread_rng};
    5910              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5911              :     use tests::storage_layer::ValuesReconstructState;
    5912              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5913              :     #[cfg(feature = "testing")]
    5914              :     use timeline::GcInfo;
    5915              :     #[cfg(feature = "testing")]
    5916              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5917              :     use timeline::{CompactOptions, DeltaLayerTestDesc};
    5918              :     use utils::id::TenantId;
    5919              : 
    5920              :     use super::*;
    5921              :     use crate::DEFAULT_PG_VERSION;
    5922              :     use crate::keyspace::KeySpaceAccum;
    5923              :     use crate::tenant::harness::*;
    5924              :     use crate::tenant::timeline::CompactFlags;
    5925              : 
    5926              :     static TEST_KEY: Lazy<Key> =
    5927           36 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5928              : 
    5929              :     #[tokio::test]
    5930            4 :     async fn test_basic() -> anyhow::Result<()> {
    5931            4 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    5932            4 :         let tline = tenant
    5933            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    5934            4 :             .await?;
    5935            4 : 
    5936            4 :         let mut writer = tline.writer().await;
    5937            4 :         writer
    5938            4 :             .put(
    5939            4 :                 *TEST_KEY,
    5940            4 :                 Lsn(0x10),
    5941            4 :                 &Value::Image(test_img("foo at 0x10")),
    5942            4 :                 &ctx,
    5943            4 :             )
    5944            4 :             .await?;
    5945            4 :         writer.finish_write(Lsn(0x10));
    5946            4 :         drop(writer);
    5947            4 : 
    5948            4 :         let mut writer = tline.writer().await;
    5949            4 :         writer
    5950            4 :             .put(
    5951            4 :                 *TEST_KEY,
    5952            4 :                 Lsn(0x20),
    5953            4 :                 &Value::Image(test_img("foo at 0x20")),
    5954            4 :                 &ctx,
    5955            4 :             )
    5956            4 :             .await?;
    5957            4 :         writer.finish_write(Lsn(0x20));
    5958            4 :         drop(writer);
    5959            4 : 
    5960            4 :         assert_eq!(
    5961            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    5962            4 :             test_img("foo at 0x10")
    5963            4 :         );
    5964            4 :         assert_eq!(
    5965            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    5966            4 :             test_img("foo at 0x10")
    5967            4 :         );
    5968            4 :         assert_eq!(
    5969            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    5970            4 :             test_img("foo at 0x20")
    5971            4 :         );
    5972            4 : 
    5973            4 :         Ok(())
    5974            4 :     }
    5975              : 
    5976              :     #[tokio::test]
    5977            4 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    5978            4 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    5979            4 :             .await?
    5980            4 :             .load()
    5981            4 :             .await;
    5982            4 :         let _ = tenant
    5983            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5984            4 :             .await?;
    5985            4 : 
    5986            4 :         match tenant
    5987            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    5988            4 :             .await
    5989            4 :         {
    5990            4 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    5991            4 :             Err(e) => assert_eq!(
    5992            4 :                 e.to_string(),
    5993            4 :                 "timeline already exists with different parameters".to_string()
    5994            4 :             ),
    5995            4 :         }
    5996            4 : 
    5997            4 :         Ok(())
    5998            4 :     }
    5999              : 
    6000              :     /// Convenience function to create a page image with given string as the only content
    6001           20 :     pub fn test_value(s: &str) -> Value {
    6002           20 :         let mut buf = BytesMut::new();
    6003           20 :         buf.extend_from_slice(s.as_bytes());
    6004           20 :         Value::Image(buf.freeze())
    6005           20 :     }
    6006              : 
    6007              :     ///
    6008              :     /// Test branch creation
    6009              :     ///
    6010              :     #[tokio::test]
    6011            4 :     async fn test_branch() -> anyhow::Result<()> {
    6012            4 :         use std::str::from_utf8;
    6013            4 : 
    6014            4 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6015            4 :         let tline = tenant
    6016            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6017            4 :             .await?;
    6018            4 :         let mut writer = tline.writer().await;
    6019            4 : 
    6020            4 :         #[allow(non_snake_case)]
    6021            4 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6022            4 :         #[allow(non_snake_case)]
    6023            4 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6024            4 : 
    6025            4 :         // Insert a value on the timeline
    6026            4 :         writer
    6027            4 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6028            4 :             .await?;
    6029            4 :         writer
    6030            4 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6031            4 :             .await?;
    6032            4 :         writer.finish_write(Lsn(0x20));
    6033            4 : 
    6034            4 :         writer
    6035            4 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6036            4 :             .await?;
    6037            4 :         writer.finish_write(Lsn(0x30));
    6038            4 :         writer
    6039            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6040            4 :             .await?;
    6041            4 :         writer.finish_write(Lsn(0x40));
    6042            4 : 
    6043            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6044            4 : 
    6045            4 :         // Branch the history, modify relation differently on the new timeline
    6046            4 :         tenant
    6047            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6048            4 :             .await?;
    6049            4 :         let newtline = tenant
    6050            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6051            4 :             .expect("Should have a local timeline");
    6052            4 :         let mut new_writer = newtline.writer().await;
    6053            4 :         new_writer
    6054            4 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6055            4 :             .await?;
    6056            4 :         new_writer.finish_write(Lsn(0x40));
    6057            4 : 
    6058            4 :         // Check page contents on both branches
    6059            4 :         assert_eq!(
    6060            4 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6061            4 :             "foo at 0x40"
    6062            4 :         );
    6063            4 :         assert_eq!(
    6064            4 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6065            4 :             "bar at 0x40"
    6066            4 :         );
    6067            4 :         assert_eq!(
    6068            4 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6069            4 :             "foobar at 0x20"
    6070            4 :         );
    6071            4 : 
    6072            4 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6073            4 : 
    6074            4 :         Ok(())
    6075            4 :     }
    6076              : 
    6077           40 :     async fn make_some_layers(
    6078           40 :         tline: &Timeline,
    6079           40 :         start_lsn: Lsn,
    6080           40 :         ctx: &RequestContext,
    6081           40 :     ) -> anyhow::Result<()> {
    6082           40 :         let mut lsn = start_lsn;
    6083              :         {
    6084           40 :             let mut writer = tline.writer().await;
    6085              :             // Create a relation on the timeline
    6086           40 :             writer
    6087           40 :                 .put(
    6088           40 :                     *TEST_KEY,
    6089           40 :                     lsn,
    6090           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6091           40 :                     ctx,
    6092           40 :                 )
    6093           40 :                 .await?;
    6094           40 :             writer.finish_write(lsn);
    6095           40 :             lsn += 0x10;
    6096           40 :             writer
    6097           40 :                 .put(
    6098           40 :                     *TEST_KEY,
    6099           40 :                     lsn,
    6100           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6101           40 :                     ctx,
    6102           40 :                 )
    6103           40 :                 .await?;
    6104           40 :             writer.finish_write(lsn);
    6105           40 :             lsn += 0x10;
    6106           40 :         }
    6107           40 :         tline.freeze_and_flush().await?;
    6108              :         {
    6109           40 :             let mut writer = tline.writer().await;
    6110           40 :             writer
    6111           40 :                 .put(
    6112           40 :                     *TEST_KEY,
    6113           40 :                     lsn,
    6114           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6115           40 :                     ctx,
    6116           40 :                 )
    6117           40 :                 .await?;
    6118           40 :             writer.finish_write(lsn);
    6119           40 :             lsn += 0x10;
    6120           40 :             writer
    6121           40 :                 .put(
    6122           40 :                     *TEST_KEY,
    6123           40 :                     lsn,
    6124           40 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6125           40 :                     ctx,
    6126           40 :                 )
    6127           40 :                 .await?;
    6128           40 :             writer.finish_write(lsn);
    6129           40 :         }
    6130           40 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6131           40 :     }
    6132              : 
    6133              :     #[tokio::test(start_paused = true)]
    6134            4 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6135            4 :         let (tenant, ctx) =
    6136            4 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6137            4 :                 .await?
    6138            4 :                 .load()
    6139            4 :                 .await;
    6140            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6141            4 :         // initial transition into AttachedSingle.
    6142            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6143            4 :         tokio::time::resume();
    6144            4 :         let tline = tenant
    6145            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6146            4 :             .await?;
    6147            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6148            4 : 
    6149            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6150            4 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6151            4 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6152            4 :         // below should fail.
    6153            4 :         tenant
    6154            4 :             .gc_iteration(
    6155            4 :                 Some(TIMELINE_ID),
    6156            4 :                 0x10,
    6157            4 :                 Duration::ZERO,
    6158            4 :                 &CancellationToken::new(),
    6159            4 :                 &ctx,
    6160            4 :             )
    6161            4 :             .await?;
    6162            4 : 
    6163            4 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6164            4 :         match tenant
    6165            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6166            4 :             .await
    6167            4 :         {
    6168            4 :             Ok(_) => panic!("branching should have failed"),
    6169            4 :             Err(err) => {
    6170            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6171            4 :                     panic!("wrong error type")
    6172            4 :                 };
    6173            4 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6174            4 :                 assert!(
    6175            4 :                     err.source()
    6176            4 :                         .unwrap()
    6177            4 :                         .to_string()
    6178            4 :                         .contains("we might've already garbage collected needed data")
    6179            4 :                 )
    6180            4 :             }
    6181            4 :         }
    6182            4 : 
    6183            4 :         Ok(())
    6184            4 :     }
    6185              : 
    6186              :     #[tokio::test]
    6187            4 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6188            4 :         let (tenant, ctx) =
    6189            4 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6190            4 :                 .await?
    6191            4 :                 .load()
    6192            4 :                 .await;
    6193            4 : 
    6194            4 :         let tline = tenant
    6195            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6196            4 :             .await?;
    6197            4 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6198            4 :         match tenant
    6199            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6200            4 :             .await
    6201            4 :         {
    6202            4 :             Ok(_) => panic!("branching should have failed"),
    6203            4 :             Err(err) => {
    6204            4 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6205            4 :                     panic!("wrong error type");
    6206            4 :                 };
    6207            4 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6208            4 :                 assert!(
    6209            4 :                     &err.source()
    6210            4 :                         .unwrap()
    6211            4 :                         .to_string()
    6212            4 :                         .contains("is earlier than latest GC cutoff")
    6213            4 :                 );
    6214            4 :             }
    6215            4 :         }
    6216            4 : 
    6217            4 :         Ok(())
    6218            4 :     }
    6219              : 
    6220              :     /*
    6221              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6222              :     // remove the old value, we'd need to work a little harder
    6223              :     #[tokio::test]
    6224              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6225              :         let repo =
    6226              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6227              :             .load();
    6228              : 
    6229              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6230              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6231              : 
    6232              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6233              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6234              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6235              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6236              :             Ok(_) => panic!("request for page should have failed"),
    6237              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6238              :         }
    6239              :         Ok(())
    6240              :     }
    6241              :      */
    6242              : 
    6243              :     #[tokio::test]
    6244            4 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6245            4 :         let (tenant, ctx) =
    6246            4 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6247            4 :                 .await?
    6248            4 :                 .load()
    6249            4 :                 .await;
    6250            4 :         let tline = tenant
    6251            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6252            4 :             .await?;
    6253            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6254            4 : 
    6255            4 :         tenant
    6256            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6257            4 :             .await?;
    6258            4 :         let newtline = tenant
    6259            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6260            4 :             .expect("Should have a local timeline");
    6261            4 : 
    6262            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6263            4 : 
    6264            4 :         tline.set_broken("test".to_owned());
    6265            4 : 
    6266            4 :         tenant
    6267            4 :             .gc_iteration(
    6268            4 :                 Some(TIMELINE_ID),
    6269            4 :                 0x10,
    6270            4 :                 Duration::ZERO,
    6271            4 :                 &CancellationToken::new(),
    6272            4 :                 &ctx,
    6273            4 :             )
    6274            4 :             .await?;
    6275            4 : 
    6276            4 :         // The branchpoints should contain all timelines, even ones marked
    6277            4 :         // as Broken.
    6278            4 :         {
    6279            4 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6280            4 :             assert_eq!(branchpoints.len(), 1);
    6281            4 :             assert_eq!(
    6282            4 :                 branchpoints[0],
    6283            4 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6284            4 :             );
    6285            4 :         }
    6286            4 : 
    6287            4 :         // You can read the key from the child branch even though the parent is
    6288            4 :         // Broken, as long as you don't need to access data from the parent.
    6289            4 :         assert_eq!(
    6290            4 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6291            4 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6292            4 :         );
    6293            4 : 
    6294            4 :         // This needs to traverse to the parent, and fails.
    6295            4 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6296            4 :         assert!(
    6297            4 :             err.to_string().starts_with(&format!(
    6298            4 :                 "bad state on timeline {}: Broken",
    6299            4 :                 tline.timeline_id
    6300            4 :             )),
    6301            4 :             "{err}"
    6302            4 :         );
    6303            4 : 
    6304            4 :         Ok(())
    6305            4 :     }
    6306              : 
    6307              :     #[tokio::test]
    6308            4 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6309            4 :         let (tenant, ctx) =
    6310            4 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6311            4 :                 .await?
    6312            4 :                 .load()
    6313            4 :                 .await;
    6314            4 :         let tline = tenant
    6315            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6316            4 :             .await?;
    6317            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6318            4 : 
    6319            4 :         tenant
    6320            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6321            4 :             .await?;
    6322            4 :         let newtline = tenant
    6323            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6324            4 :             .expect("Should have a local timeline");
    6325            4 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6326            4 :         tenant
    6327            4 :             .gc_iteration(
    6328            4 :                 Some(TIMELINE_ID),
    6329            4 :                 0x10,
    6330            4 :                 Duration::ZERO,
    6331            4 :                 &CancellationToken::new(),
    6332            4 :                 &ctx,
    6333            4 :             )
    6334            4 :             .await?;
    6335            4 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6336            4 : 
    6337            4 :         Ok(())
    6338            4 :     }
    6339              :     #[tokio::test]
    6340            4 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6341            4 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6342            4 :             .await?
    6343            4 :             .load()
    6344            4 :             .await;
    6345            4 :         let tline = tenant
    6346            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6347            4 :             .await?;
    6348            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6349            4 : 
    6350            4 :         tenant
    6351            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6352            4 :             .await?;
    6353            4 :         let newtline = tenant
    6354            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6355            4 :             .expect("Should have a local timeline");
    6356            4 : 
    6357            4 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6358            4 : 
    6359            4 :         // run gc on parent
    6360            4 :         tenant
    6361            4 :             .gc_iteration(
    6362            4 :                 Some(TIMELINE_ID),
    6363            4 :                 0x10,
    6364            4 :                 Duration::ZERO,
    6365            4 :                 &CancellationToken::new(),
    6366            4 :                 &ctx,
    6367            4 :             )
    6368            4 :             .await?;
    6369            4 : 
    6370            4 :         // Check that the data is still accessible on the branch.
    6371            4 :         assert_eq!(
    6372            4 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6373            4 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6374            4 :         );
    6375            4 : 
    6376            4 :         Ok(())
    6377            4 :     }
    6378              : 
    6379              :     #[tokio::test]
    6380            4 :     async fn timeline_load() -> anyhow::Result<()> {
    6381            4 :         const TEST_NAME: &str = "timeline_load";
    6382            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6383            4 :         {
    6384            4 :             let (tenant, ctx) = harness.load().await;
    6385            4 :             let tline = tenant
    6386            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6387            4 :                 .await?;
    6388            4 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6389            4 :             // so that all uploads finish & we can call harness.load() below again
    6390            4 :             tenant
    6391            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6392            4 :                 .instrument(harness.span())
    6393            4 :                 .await
    6394            4 :                 .ok()
    6395            4 :                 .unwrap();
    6396            4 :         }
    6397            4 : 
    6398            4 :         let (tenant, _ctx) = harness.load().await;
    6399            4 :         tenant
    6400            4 :             .get_timeline(TIMELINE_ID, true)
    6401            4 :             .expect("cannot load timeline");
    6402            4 : 
    6403            4 :         Ok(())
    6404            4 :     }
    6405              : 
    6406              :     #[tokio::test]
    6407            4 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6408            4 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6409            4 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6410            4 :         // create two timelines
    6411            4 :         {
    6412            4 :             let (tenant, ctx) = harness.load().await;
    6413            4 :             let tline = tenant
    6414            4 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6415            4 :                 .await?;
    6416            4 : 
    6417            4 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6418            4 : 
    6419            4 :             let child_tline = tenant
    6420            4 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6421            4 :                 .await?;
    6422            4 :             child_tline.set_state(TimelineState::Active);
    6423            4 : 
    6424            4 :             let newtline = tenant
    6425            4 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6426            4 :                 .expect("Should have a local timeline");
    6427            4 : 
    6428            4 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6429            4 : 
    6430            4 :             // so that all uploads finish & we can call harness.load() below again
    6431            4 :             tenant
    6432            4 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6433            4 :                 .instrument(harness.span())
    6434            4 :                 .await
    6435            4 :                 .ok()
    6436            4 :                 .unwrap();
    6437            4 :         }
    6438            4 : 
    6439            4 :         // check that both of them are initially unloaded
    6440            4 :         let (tenant, _ctx) = harness.load().await;
    6441            4 : 
    6442            4 :         // check that both, child and ancestor are loaded
    6443            4 :         let _child_tline = tenant
    6444            4 :             .get_timeline(NEW_TIMELINE_ID, true)
    6445            4 :             .expect("cannot get child timeline loaded");
    6446            4 : 
    6447            4 :         let _ancestor_tline = tenant
    6448            4 :             .get_timeline(TIMELINE_ID, true)
    6449            4 :             .expect("cannot get ancestor timeline loaded");
    6450            4 : 
    6451            4 :         Ok(())
    6452            4 :     }
    6453              : 
    6454              :     #[tokio::test]
    6455            4 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6456            4 :         use storage_layer::AsLayerDesc;
    6457            4 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6458            4 :             .await?
    6459            4 :             .load()
    6460            4 :             .await;
    6461            4 :         let tline = tenant
    6462            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6463            4 :             .await?;
    6464            4 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6465            4 : 
    6466            4 :         let layer_map = tline.layers.read().await;
    6467            4 :         let level0_deltas = layer_map
    6468            4 :             .layer_map()?
    6469            4 :             .level0_deltas()
    6470            4 :             .iter()
    6471            8 :             .map(|desc| layer_map.get_from_desc(desc))
    6472            4 :             .collect::<Vec<_>>();
    6473            4 : 
    6474            4 :         assert!(!level0_deltas.is_empty());
    6475            4 : 
    6476           12 :         for delta in level0_deltas {
    6477            4 :             // Ensure we are dumping a delta layer here
    6478            8 :             assert!(delta.layer_desc().is_delta);
    6479            8 :             delta.dump(true, &ctx).await.unwrap();
    6480            4 :         }
    6481            4 : 
    6482            4 :         Ok(())
    6483            4 :     }
    6484              : 
    6485              :     #[tokio::test]
    6486            4 :     async fn test_images() -> anyhow::Result<()> {
    6487            4 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6488            4 :         let tline = tenant
    6489            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6490            4 :             .await?;
    6491            4 : 
    6492            4 :         let mut writer = tline.writer().await;
    6493            4 :         writer
    6494            4 :             .put(
    6495            4 :                 *TEST_KEY,
    6496            4 :                 Lsn(0x10),
    6497            4 :                 &Value::Image(test_img("foo at 0x10")),
    6498            4 :                 &ctx,
    6499            4 :             )
    6500            4 :             .await?;
    6501            4 :         writer.finish_write(Lsn(0x10));
    6502            4 :         drop(writer);
    6503            4 : 
    6504            4 :         tline.freeze_and_flush().await?;
    6505            4 :         tline
    6506            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6507            4 :             .await?;
    6508            4 : 
    6509            4 :         let mut writer = tline.writer().await;
    6510            4 :         writer
    6511            4 :             .put(
    6512            4 :                 *TEST_KEY,
    6513            4 :                 Lsn(0x20),
    6514            4 :                 &Value::Image(test_img("foo at 0x20")),
    6515            4 :                 &ctx,
    6516            4 :             )
    6517            4 :             .await?;
    6518            4 :         writer.finish_write(Lsn(0x20));
    6519            4 :         drop(writer);
    6520            4 : 
    6521            4 :         tline.freeze_and_flush().await?;
    6522            4 :         tline
    6523            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6524            4 :             .await?;
    6525            4 : 
    6526            4 :         let mut writer = tline.writer().await;
    6527            4 :         writer
    6528            4 :             .put(
    6529            4 :                 *TEST_KEY,
    6530            4 :                 Lsn(0x30),
    6531            4 :                 &Value::Image(test_img("foo at 0x30")),
    6532            4 :                 &ctx,
    6533            4 :             )
    6534            4 :             .await?;
    6535            4 :         writer.finish_write(Lsn(0x30));
    6536            4 :         drop(writer);
    6537            4 : 
    6538            4 :         tline.freeze_and_flush().await?;
    6539            4 :         tline
    6540            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6541            4 :             .await?;
    6542            4 : 
    6543            4 :         let mut writer = tline.writer().await;
    6544            4 :         writer
    6545            4 :             .put(
    6546            4 :                 *TEST_KEY,
    6547            4 :                 Lsn(0x40),
    6548            4 :                 &Value::Image(test_img("foo at 0x40")),
    6549            4 :                 &ctx,
    6550            4 :             )
    6551            4 :             .await?;
    6552            4 :         writer.finish_write(Lsn(0x40));
    6553            4 :         drop(writer);
    6554            4 : 
    6555            4 :         tline.freeze_and_flush().await?;
    6556            4 :         tline
    6557            4 :             .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
    6558            4 :             .await?;
    6559            4 : 
    6560            4 :         assert_eq!(
    6561            4 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6562            4 :             test_img("foo at 0x10")
    6563            4 :         );
    6564            4 :         assert_eq!(
    6565            4 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6566            4 :             test_img("foo at 0x10")
    6567            4 :         );
    6568            4 :         assert_eq!(
    6569            4 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6570            4 :             test_img("foo at 0x20")
    6571            4 :         );
    6572            4 :         assert_eq!(
    6573            4 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6574            4 :             test_img("foo at 0x30")
    6575            4 :         );
    6576            4 :         assert_eq!(
    6577            4 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6578            4 :             test_img("foo at 0x40")
    6579            4 :         );
    6580            4 : 
    6581            4 :         Ok(())
    6582            4 :     }
    6583              : 
    6584            8 :     async fn bulk_insert_compact_gc(
    6585            8 :         tenant: &Tenant,
    6586            8 :         timeline: &Arc<Timeline>,
    6587            8 :         ctx: &RequestContext,
    6588            8 :         lsn: Lsn,
    6589            8 :         repeat: usize,
    6590            8 :         key_count: usize,
    6591            8 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6592            8 :         let compact = true;
    6593            8 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6594            8 :     }
    6595              : 
    6596           16 :     async fn bulk_insert_maybe_compact_gc(
    6597           16 :         tenant: &Tenant,
    6598           16 :         timeline: &Arc<Timeline>,
    6599           16 :         ctx: &RequestContext,
    6600           16 :         mut lsn: Lsn,
    6601           16 :         repeat: usize,
    6602           16 :         key_count: usize,
    6603           16 :         compact: bool,
    6604           16 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6605           16 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6606           16 : 
    6607           16 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6608           16 :         let mut blknum = 0;
    6609           16 : 
    6610           16 :         // Enforce that key range is monotonously increasing
    6611           16 :         let mut keyspace = KeySpaceAccum::new();
    6612           16 : 
    6613           16 :         let cancel = CancellationToken::new();
    6614           16 : 
    6615           16 :         for _ in 0..repeat {
    6616          800 :             for _ in 0..key_count {
    6617      8000000 :                 test_key.field6 = blknum;
    6618      8000000 :                 let mut writer = timeline.writer().await;
    6619      8000000 :                 writer
    6620      8000000 :                     .put(
    6621      8000000 :                         test_key,
    6622      8000000 :                         lsn,
    6623      8000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6624      8000000 :                         ctx,
    6625      8000000 :                     )
    6626      8000000 :                     .await?;
    6627      8000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    6628      8000000 :                 writer.finish_write(lsn);
    6629      8000000 :                 drop(writer);
    6630      8000000 : 
    6631      8000000 :                 keyspace.add_key(test_key);
    6632      8000000 : 
    6633      8000000 :                 lsn = Lsn(lsn.0 + 0x10);
    6634      8000000 :                 blknum += 1;
    6635              :             }
    6636              : 
    6637          800 :             timeline.freeze_and_flush().await?;
    6638          800 :             if compact {
    6639              :                 // this requires timeline to be &Arc<Timeline>
    6640          400 :                 timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
    6641          400 :             }
    6642              : 
    6643              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    6644              :             // originally was.
    6645          800 :             let res = tenant
    6646          800 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    6647          800 :                 .await?;
    6648              : 
    6649          800 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    6650              :         }
    6651              : 
    6652           16 :         Ok(inserted)
    6653           16 :     }
    6654              : 
    6655              :     //
    6656              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    6657              :     // Repeat 50 times.
    6658              :     //
    6659              :     #[tokio::test]
    6660            4 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    6661            4 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    6662            4 :         let (tenant, ctx) = harness.load().await;
    6663            4 :         let tline = tenant
    6664            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6665            4 :             .await?;
    6666            4 : 
    6667            4 :         let lsn = Lsn(0x10);
    6668            4 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6669            4 : 
    6670            4 :         Ok(())
    6671            4 :     }
    6672              : 
    6673              :     // Test the vectored get real implementation against a simple sequential implementation.
    6674              :     //
    6675              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    6676              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    6677              :     // grow to the right on the X axis.
    6678              :     //                       [Delta]
    6679              :     //                 [Delta]
    6680              :     //           [Delta]
    6681              :     //    [Delta]
    6682              :     // ------------ Image ---------------
    6683              :     //
    6684              :     // After layer generation we pick the ranges to query as follows:
    6685              :     // 1. The beginning of each delta layer
    6686              :     // 2. At the seam between two adjacent delta layers
    6687              :     //
    6688              :     // There's one major downside to this test: delta layers only contains images,
    6689              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    6690              :     #[tokio::test]
    6691            4 :     async fn test_get_vectored() -> anyhow::Result<()> {
    6692            4 :         let harness = TenantHarness::create("test_get_vectored").await?;
    6693            4 :         let (tenant, ctx) = harness.load().await;
    6694            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6695            4 :         let tline = tenant
    6696            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6697            4 :             .await?;
    6698            4 : 
    6699            4 :         let lsn = Lsn(0x10);
    6700            4 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    6701            4 : 
    6702            4 :         let guard = tline.layers.read().await;
    6703            4 :         let lm = guard.layer_map()?;
    6704            4 : 
    6705            4 :         lm.dump(true, &ctx).await?;
    6706            4 : 
    6707            4 :         let mut reads = Vec::new();
    6708            4 :         let mut prev = None;
    6709           24 :         lm.iter_historic_layers().for_each(|desc| {
    6710           24 :             if !desc.is_delta() {
    6711            4 :                 prev = Some(desc.clone());
    6712            4 :                 return;
    6713           20 :             }
    6714           20 : 
    6715           20 :             let start = desc.key_range.start;
    6716           20 :             let end = desc
    6717           20 :                 .key_range
    6718           20 :                 .start
    6719           20 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    6720           20 :             reads.push(KeySpace {
    6721           20 :                 ranges: vec![start..end],
    6722           20 :             });
    6723            4 : 
    6724           20 :             if let Some(prev) = &prev {
    6725           20 :                 if !prev.is_delta() {
    6726           20 :                     return;
    6727            4 :                 }
    6728            0 : 
    6729            0 :                 let first_range = Key {
    6730            0 :                     field6: prev.key_range.end.field6 - 4,
    6731            0 :                     ..prev.key_range.end
    6732            0 :                 }..prev.key_range.end;
    6733            0 : 
    6734            0 :                 let second_range = desc.key_range.start..Key {
    6735            0 :                     field6: desc.key_range.start.field6 + 4,
    6736            0 :                     ..desc.key_range.start
    6737            0 :                 };
    6738            0 : 
    6739            0 :                 reads.push(KeySpace {
    6740            0 :                     ranges: vec![first_range, second_range],
    6741            0 :                 });
    6742            4 :             };
    6743            4 : 
    6744            4 :             prev = Some(desc.clone());
    6745           24 :         });
    6746            4 : 
    6747            4 :         drop(guard);
    6748            4 : 
    6749            4 :         // Pick a big LSN such that we query over all the changes.
    6750            4 :         let reads_lsn = Lsn(u64::MAX - 1);
    6751            4 : 
    6752           24 :         for read in reads {
    6753           20 :             info!("Doing vectored read on {:?}", read);
    6754            4 : 
    6755           20 :             let vectored_res = tline
    6756           20 :                 .get_vectored_impl(
    6757           20 :                     read.clone(),
    6758           20 :                     reads_lsn,
    6759           20 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    6760           20 :                     &ctx,
    6761           20 :                 )
    6762           20 :                 .await;
    6763            4 : 
    6764           20 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    6765           20 :             let mut expect_missing = false;
    6766           20 :             let mut key = read.start().unwrap();
    6767          660 :             while key != read.end().unwrap() {
    6768          640 :                 if let Some(lsns) = inserted.get(&key) {
    6769          640 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    6770          640 :                     match expected_lsn {
    6771          640 :                         Some(lsn) => {
    6772          640 :                             expected_lsns.insert(key, *lsn);
    6773          640 :                         }
    6774            4 :                         None => {
    6775            4 :                             expect_missing = true;
    6776            0 :                             break;
    6777            4 :                         }
    6778            4 :                     }
    6779            4 :                 } else {
    6780            4 :                     expect_missing = true;
    6781            0 :                     break;
    6782            4 :                 }
    6783            4 : 
    6784          640 :                 key = key.next();
    6785            4 :             }
    6786            4 : 
    6787           20 :             if expect_missing {
    6788            4 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    6789            4 :             } else {
    6790          640 :                 for (key, image) in vectored_res? {
    6791          640 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    6792          640 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    6793          640 :                     assert_eq!(image?, expected_image);
    6794            4 :                 }
    6795            4 :             }
    6796            4 :         }
    6797            4 : 
    6798            4 :         Ok(())
    6799            4 :     }
    6800              : 
    6801              :     #[tokio::test]
    6802            4 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    6803            4 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    6804            4 : 
    6805            4 :         let (tenant, ctx) = harness.load().await;
    6806            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6807            4 :         let tline = tenant
    6808            4 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    6809            4 :             .await?;
    6810            4 :         let tline = tline.raw_timeline().unwrap();
    6811            4 : 
    6812            4 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    6813            4 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    6814            4 :         modification.set_lsn(Lsn(0x1008))?;
    6815            4 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    6816            4 :         modification.commit(&ctx).await?;
    6817            4 : 
    6818            4 :         let child_timeline_id = TimelineId::generate();
    6819            4 :         tenant
    6820            4 :             .branch_timeline_test(
    6821            4 :                 tline,
    6822            4 :                 child_timeline_id,
    6823            4 :                 Some(tline.get_last_record_lsn()),
    6824            4 :                 &ctx,
    6825            4 :             )
    6826            4 :             .await?;
    6827            4 : 
    6828            4 :         let child_timeline = tenant
    6829            4 :             .get_timeline(child_timeline_id, true)
    6830            4 :             .expect("Should have the branched timeline");
    6831            4 : 
    6832            4 :         let aux_keyspace = KeySpace {
    6833            4 :             ranges: vec![NON_INHERITED_RANGE],
    6834            4 :         };
    6835            4 :         let read_lsn = child_timeline.get_last_record_lsn();
    6836            4 : 
    6837            4 :         let vectored_res = child_timeline
    6838            4 :             .get_vectored_impl(
    6839            4 :                 aux_keyspace.clone(),
    6840            4 :                 read_lsn,
    6841            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6842            4 :                 &ctx,
    6843            4 :             )
    6844            4 :             .await;
    6845            4 : 
    6846            4 :         let images = vectored_res?;
    6847            4 :         assert!(images.is_empty());
    6848            4 :         Ok(())
    6849            4 :     }
    6850              : 
    6851              :     // Test that vectored get handles layer gaps correctly
    6852              :     // by advancing into the next ancestor timeline if required.
    6853              :     //
    6854              :     // The test generates timelines that look like the diagram below.
    6855              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    6856              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    6857              :     //
    6858              :     // ```
    6859              :     //-------------------------------+
    6860              :     //                          ...  |
    6861              :     //               [   L1   ]      |
    6862              :     //     [ / L1   ]                | Child Timeline
    6863              :     // ...                           |
    6864              :     // ------------------------------+
    6865              :     //     [ X L1   ]                | Parent Timeline
    6866              :     // ------------------------------+
    6867              :     // ```
    6868              :     #[tokio::test]
    6869            4 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    6870            4 :         let tenant_conf = TenantConf {
    6871            4 :             // Make compaction deterministic
    6872            4 :             gc_period: Duration::ZERO,
    6873            4 :             compaction_period: Duration::ZERO,
    6874            4 :             // Encourage creation of L1 layers
    6875            4 :             checkpoint_distance: 16 * 1024,
    6876            4 :             compaction_target_size: 8 * 1024,
    6877            4 :             ..TenantConf::default()
    6878            4 :         };
    6879            4 : 
    6880            4 :         let harness = TenantHarness::create_custom(
    6881            4 :             "test_get_vectored_key_gap",
    6882            4 :             tenant_conf,
    6883            4 :             TenantId::generate(),
    6884            4 :             ShardIdentity::unsharded(),
    6885            4 :             Generation::new(0xdeadbeef),
    6886            4 :         )
    6887            4 :         .await?;
    6888            4 :         let (tenant, ctx) = harness.load().await;
    6889            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    6890            4 : 
    6891            4 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6892            4 :         let gap_at_key = current_key.add(100);
    6893            4 :         let mut current_lsn = Lsn(0x10);
    6894            4 : 
    6895            4 :         const KEY_COUNT: usize = 10_000;
    6896            4 : 
    6897            4 :         let timeline_id = TimelineId::generate();
    6898            4 :         let current_timeline = tenant
    6899            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    6900            4 :             .await?;
    6901            4 : 
    6902            4 :         current_lsn += 0x100;
    6903            4 : 
    6904            4 :         let mut writer = current_timeline.writer().await;
    6905            4 :         writer
    6906            4 :             .put(
    6907            4 :                 gap_at_key,
    6908            4 :                 current_lsn,
    6909            4 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    6910            4 :                 &ctx,
    6911            4 :             )
    6912            4 :             .await?;
    6913            4 :         writer.finish_write(current_lsn);
    6914            4 :         drop(writer);
    6915            4 : 
    6916            4 :         let mut latest_lsns = HashMap::new();
    6917            4 :         latest_lsns.insert(gap_at_key, current_lsn);
    6918            4 : 
    6919            4 :         current_timeline.freeze_and_flush().await?;
    6920            4 : 
    6921            4 :         let child_timeline_id = TimelineId::generate();
    6922            4 : 
    6923            4 :         tenant
    6924            4 :             .branch_timeline_test(
    6925            4 :                 &current_timeline,
    6926            4 :                 child_timeline_id,
    6927            4 :                 Some(current_lsn),
    6928            4 :                 &ctx,
    6929            4 :             )
    6930            4 :             .await?;
    6931            4 :         let child_timeline = tenant
    6932            4 :             .get_timeline(child_timeline_id, true)
    6933            4 :             .expect("Should have the branched timeline");
    6934            4 : 
    6935        40004 :         for i in 0..KEY_COUNT {
    6936        40000 :             if current_key == gap_at_key {
    6937            4 :                 current_key = current_key.next();
    6938            4 :                 continue;
    6939        39996 :             }
    6940        39996 : 
    6941        39996 :             current_lsn += 0x10;
    6942            4 : 
    6943        39996 :             let mut writer = child_timeline.writer().await;
    6944        39996 :             writer
    6945        39996 :                 .put(
    6946        39996 :                     current_key,
    6947        39996 :                     current_lsn,
    6948        39996 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    6949        39996 :                     &ctx,
    6950        39996 :                 )
    6951        39996 :                 .await?;
    6952        39996 :             writer.finish_write(current_lsn);
    6953        39996 :             drop(writer);
    6954        39996 : 
    6955        39996 :             latest_lsns.insert(current_key, current_lsn);
    6956        39996 :             current_key = current_key.next();
    6957        39996 : 
    6958        39996 :             // Flush every now and then to encourage layer file creation.
    6959        39996 :             if i % 500 == 0 {
    6960           80 :                 child_timeline.freeze_and_flush().await?;
    6961        39916 :             }
    6962            4 :         }
    6963            4 : 
    6964            4 :         child_timeline.freeze_and_flush().await?;
    6965            4 :         let mut flags = EnumSet::new();
    6966            4 :         flags.insert(CompactFlags::ForceRepartition);
    6967            4 :         child_timeline
    6968            4 :             .compact(&CancellationToken::new(), flags, &ctx)
    6969            4 :             .await?;
    6970            4 : 
    6971            4 :         let key_near_end = {
    6972            4 :             let mut tmp = current_key;
    6973            4 :             tmp.field6 -= 10;
    6974            4 :             tmp
    6975            4 :         };
    6976            4 : 
    6977            4 :         let key_near_gap = {
    6978            4 :             let mut tmp = gap_at_key;
    6979            4 :             tmp.field6 -= 10;
    6980            4 :             tmp
    6981            4 :         };
    6982            4 : 
    6983            4 :         let read = KeySpace {
    6984            4 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    6985            4 :         };
    6986            4 :         let results = child_timeline
    6987            4 :             .get_vectored_impl(
    6988            4 :                 read.clone(),
    6989            4 :                 current_lsn,
    6990            4 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    6991            4 :                 &ctx,
    6992            4 :             )
    6993            4 :             .await?;
    6994            4 : 
    6995           88 :         for (key, img_res) in results {
    6996           84 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    6997           84 :             assert_eq!(img_res?, expected);
    6998            4 :         }
    6999            4 : 
    7000            4 :         Ok(())
    7001            4 :     }
    7002              : 
    7003              :     // Test that vectored get descends into ancestor timelines correctly and
    7004              :     // does not return an image that's newer than requested.
    7005              :     //
    7006              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7007              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7008              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7009              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7010              :     // order to avoid returning an image that's too new. The test below constructs such
    7011              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7012              :     // ```
    7013              :     //    LSN
    7014              :     //     ^
    7015              :     //     |
    7016              :     //     |
    7017              :     // 500 | --------------------------------------> branch point
    7018              :     // 400 |        X
    7019              :     // 300 |        X
    7020              :     // 200 | --------------------------------------> requested lsn
    7021              :     // 100 |        X
    7022              :     //     |---------------------------------------> Key
    7023              :     //              |
    7024              :     //              ------> requested key
    7025              :     //
    7026              :     // Legend:
    7027              :     // * X - page images
    7028              :     // ```
    7029              :     #[tokio::test]
    7030            4 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7031            4 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7032            4 :         let (tenant, ctx) = harness.load().await;
    7033            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7034            4 : 
    7035            4 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7036            4 :         let end_key = start_key.add(1000);
    7037            4 :         let child_gap_at_key = start_key.add(500);
    7038            4 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7039            4 : 
    7040            4 :         let mut current_lsn = Lsn(0x10);
    7041            4 : 
    7042            4 :         let timeline_id = TimelineId::generate();
    7043            4 :         let parent_timeline = tenant
    7044            4 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7045            4 :             .await?;
    7046            4 : 
    7047            4 :         current_lsn += 0x100;
    7048            4 : 
    7049           16 :         for _ in 0..3 {
    7050           12 :             let mut key = start_key;
    7051        12012 :             while key < end_key {
    7052        12000 :                 current_lsn += 0x10;
    7053        12000 : 
    7054        12000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    7055            4 : 
    7056        12000 :                 let mut writer = parent_timeline.writer().await;
    7057        12000 :                 writer
    7058        12000 :                     .put(
    7059        12000 :                         key,
    7060        12000 :                         current_lsn,
    7061        12000 :                         &Value::Image(test_img(&image_value)),
    7062        12000 :                         &ctx,
    7063        12000 :                     )
    7064        12000 :                     .await?;
    7065        12000 :                 writer.finish_write(current_lsn);
    7066        12000 : 
    7067        12000 :                 if key == child_gap_at_key {
    7068           12 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7069        11988 :                 }
    7070            4 : 
    7071        12000 :                 key = key.next();
    7072            4 :             }
    7073            4 : 
    7074           12 :             parent_timeline.freeze_and_flush().await?;
    7075            4 :         }
    7076            4 : 
    7077            4 :         let child_timeline_id = TimelineId::generate();
    7078            4 : 
    7079            4 :         let child_timeline = tenant
    7080            4 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7081            4 :             .await?;
    7082            4 : 
    7083            4 :         let mut key = start_key;
    7084         4004 :         while key < end_key {
    7085         4000 :             if key == child_gap_at_key {
    7086            4 :                 key = key.next();
    7087            4 :                 continue;
    7088         3996 :             }
    7089         3996 : 
    7090         3996 :             current_lsn += 0x10;
    7091            4 : 
    7092         3996 :             let mut writer = child_timeline.writer().await;
    7093         3996 :             writer
    7094         3996 :                 .put(
    7095         3996 :                     key,
    7096         3996 :                     current_lsn,
    7097         3996 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    7098         3996 :                     &ctx,
    7099         3996 :                 )
    7100         3996 :                 .await?;
    7101         3996 :             writer.finish_write(current_lsn);
    7102         3996 : 
    7103         3996 :             key = key.next();
    7104            4 :         }
    7105            4 : 
    7106            4 :         child_timeline.freeze_and_flush().await?;
    7107            4 : 
    7108            4 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7109            4 :         let mut query_lsns = Vec::new();
    7110           12 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7111           72 :             for offset in lsn_offsets {
    7112           60 :                 query_lsns.push(Lsn(image_lsn
    7113           60 :                     .0
    7114           60 :                     .checked_add_signed(offset)
    7115           60 :                     .expect("Shouldn't overflow")));
    7116           60 :             }
    7117            4 :         }
    7118            4 : 
    7119           64 :         for query_lsn in query_lsns {
    7120           60 :             let results = child_timeline
    7121           60 :                 .get_vectored_impl(
    7122           60 :                     KeySpace {
    7123           60 :                         ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7124           60 :                     },
    7125           60 :                     query_lsn,
    7126           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7127           60 :                     &ctx,
    7128           60 :                 )
    7129           60 :                 .await;
    7130            4 : 
    7131           60 :             let expected_item = parent_gap_lsns
    7132           60 :                 .iter()
    7133           60 :                 .rev()
    7134          136 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7135           60 : 
    7136           60 :             info!(
    7137            4 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7138            4 :                 query_lsn, expected_item
    7139            4 :             );
    7140            4 : 
    7141           60 :             match expected_item {
    7142           52 :                 Some((_, img_value)) => {
    7143           52 :                     let key_results = results.expect("No vectored get error expected");
    7144           52 :                     let key_result = &key_results[&child_gap_at_key];
    7145           52 :                     let returned_img = key_result
    7146           52 :                         .as_ref()
    7147           52 :                         .expect("No page reconstruct error expected");
    7148           52 : 
    7149           52 :                     info!(
    7150            4 :                         "Vectored read at LSN {} returned image {}",
    7151            0 :                         query_lsn,
    7152            0 :                         std::str::from_utf8(returned_img)?
    7153            4 :                     );
    7154           52 :                     assert_eq!(*returned_img, test_img(img_value));
    7155            4 :                 }
    7156            4 :                 None => {
    7157            8 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7158            4 :                 }
    7159            4 :             }
    7160            4 :         }
    7161            4 : 
    7162            4 :         Ok(())
    7163            4 :     }
    7164              : 
    7165              :     #[tokio::test]
    7166            4 :     async fn test_random_updates() -> anyhow::Result<()> {
    7167            4 :         let names_algorithms = [
    7168            4 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7169            4 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7170            4 :         ];
    7171           12 :         for (name, algorithm) in names_algorithms {
    7172            8 :             test_random_updates_algorithm(name, algorithm).await?;
    7173            4 :         }
    7174            4 :         Ok(())
    7175            4 :     }
    7176              : 
    7177            8 :     async fn test_random_updates_algorithm(
    7178            8 :         name: &'static str,
    7179            8 :         compaction_algorithm: CompactionAlgorithm,
    7180            8 :     ) -> anyhow::Result<()> {
    7181            8 :         let mut harness = TenantHarness::create(name).await?;
    7182            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7183            8 :             kind: compaction_algorithm,
    7184            8 :         };
    7185            8 :         let (tenant, ctx) = harness.load().await;
    7186            8 :         let tline = tenant
    7187            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7188            8 :             .await?;
    7189              : 
    7190              :         const NUM_KEYS: usize = 1000;
    7191            8 :         let cancel = CancellationToken::new();
    7192            8 : 
    7193            8 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7194            8 :         let mut test_key_end = test_key;
    7195            8 :         test_key_end.field6 = NUM_KEYS as u32;
    7196            8 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7197            8 : 
    7198            8 :         let mut keyspace = KeySpaceAccum::new();
    7199            8 : 
    7200            8 :         // Track when each page was last modified. Used to assert that
    7201            8 :         // a read sees the latest page version.
    7202            8 :         let mut updated = [Lsn(0); NUM_KEYS];
    7203            8 : 
    7204            8 :         let mut lsn = Lsn(0x10);
    7205              :         #[allow(clippy::needless_range_loop)]
    7206         8008 :         for blknum in 0..NUM_KEYS {
    7207         8000 :             lsn = Lsn(lsn.0 + 0x10);
    7208         8000 :             test_key.field6 = blknum as u32;
    7209         8000 :             let mut writer = tline.writer().await;
    7210         8000 :             writer
    7211         8000 :                 .put(
    7212         8000 :                     test_key,
    7213         8000 :                     lsn,
    7214         8000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7215         8000 :                     &ctx,
    7216         8000 :                 )
    7217         8000 :                 .await?;
    7218         8000 :             writer.finish_write(lsn);
    7219         8000 :             updated[blknum] = lsn;
    7220         8000 :             drop(writer);
    7221         8000 : 
    7222         8000 :             keyspace.add_key(test_key);
    7223              :         }
    7224              : 
    7225          408 :         for _ in 0..50 {
    7226       400400 :             for _ in 0..NUM_KEYS {
    7227       400000 :                 lsn = Lsn(lsn.0 + 0x10);
    7228       400000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7229       400000 :                 test_key.field6 = blknum as u32;
    7230       400000 :                 let mut writer = tline.writer().await;
    7231       400000 :                 writer
    7232       400000 :                     .put(
    7233       400000 :                         test_key,
    7234       400000 :                         lsn,
    7235       400000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7236       400000 :                         &ctx,
    7237       400000 :                     )
    7238       400000 :                     .await?;
    7239       400000 :                 writer.finish_write(lsn);
    7240       400000 :                 drop(writer);
    7241       400000 :                 updated[blknum] = lsn;
    7242              :             }
    7243              : 
    7244              :             // Read all the blocks
    7245       400000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7246       400000 :                 test_key.field6 = blknum as u32;
    7247       400000 :                 assert_eq!(
    7248       400000 :                     tline.get(test_key, lsn, &ctx).await?,
    7249       400000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7250              :                 );
    7251              :             }
    7252              : 
    7253              :             // Perform a cycle of flush, and GC
    7254          400 :             tline.freeze_and_flush().await?;
    7255          400 :             tenant
    7256          400 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7257          400 :                 .await?;
    7258              :         }
    7259              : 
    7260            8 :         Ok(())
    7261            8 :     }
    7262              : 
    7263              :     #[tokio::test]
    7264            4 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7265            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7266            4 :             .await?
    7267            4 :             .load()
    7268            4 :             .await;
    7269            4 :         let mut tline = tenant
    7270            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7271            4 :             .await?;
    7272            4 : 
    7273            4 :         const NUM_KEYS: usize = 1000;
    7274            4 : 
    7275            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7276            4 : 
    7277            4 :         let mut keyspace = KeySpaceAccum::new();
    7278            4 : 
    7279            4 :         let cancel = CancellationToken::new();
    7280            4 : 
    7281            4 :         // Track when each page was last modified. Used to assert that
    7282            4 :         // a read sees the latest page version.
    7283            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7284            4 : 
    7285            4 :         let mut lsn = Lsn(0x10);
    7286            4 :         #[allow(clippy::needless_range_loop)]
    7287         4004 :         for blknum in 0..NUM_KEYS {
    7288         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7289         4000 :             test_key.field6 = blknum as u32;
    7290         4000 :             let mut writer = tline.writer().await;
    7291         4000 :             writer
    7292         4000 :                 .put(
    7293         4000 :                     test_key,
    7294         4000 :                     lsn,
    7295         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7296         4000 :                     &ctx,
    7297         4000 :                 )
    7298         4000 :                 .await?;
    7299         4000 :             writer.finish_write(lsn);
    7300         4000 :             updated[blknum] = lsn;
    7301         4000 :             drop(writer);
    7302         4000 : 
    7303         4000 :             keyspace.add_key(test_key);
    7304            4 :         }
    7305            4 : 
    7306          204 :         for _ in 0..50 {
    7307          200 :             let new_tline_id = TimelineId::generate();
    7308          200 :             tenant
    7309          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7310          200 :                 .await?;
    7311          200 :             tline = tenant
    7312          200 :                 .get_timeline(new_tline_id, true)
    7313          200 :                 .expect("Should have the branched timeline");
    7314            4 : 
    7315       200200 :             for _ in 0..NUM_KEYS {
    7316       200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7317       200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7318       200000 :                 test_key.field6 = blknum as u32;
    7319       200000 :                 let mut writer = tline.writer().await;
    7320       200000 :                 writer
    7321       200000 :                     .put(
    7322       200000 :                         test_key,
    7323       200000 :                         lsn,
    7324       200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7325       200000 :                         &ctx,
    7326       200000 :                     )
    7327       200000 :                     .await?;
    7328       200000 :                 println!("updating {} at {}", blknum, lsn);
    7329       200000 :                 writer.finish_write(lsn);
    7330       200000 :                 drop(writer);
    7331       200000 :                 updated[blknum] = lsn;
    7332            4 :             }
    7333            4 : 
    7334            4 :             // Read all the blocks
    7335       200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7336       200000 :                 test_key.field6 = blknum as u32;
    7337       200000 :                 assert_eq!(
    7338       200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7339       200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7340            4 :                 );
    7341            4 :             }
    7342            4 : 
    7343            4 :             // Perform a cycle of flush, compact, and GC
    7344          200 :             tline.freeze_and_flush().await?;
    7345          200 :             tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7346          200 :             tenant
    7347          200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7348          200 :                 .await?;
    7349            4 :         }
    7350            4 : 
    7351            4 :         Ok(())
    7352            4 :     }
    7353              : 
    7354              :     #[tokio::test]
    7355            4 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7356            4 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7357            4 :             .await?
    7358            4 :             .load()
    7359            4 :             .await;
    7360            4 :         let mut tline = tenant
    7361            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7362            4 :             .await?;
    7363            4 : 
    7364            4 :         const NUM_KEYS: usize = 100;
    7365            4 :         const NUM_TLINES: usize = 50;
    7366            4 : 
    7367            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7368            4 :         // Track page mutation lsns across different timelines.
    7369            4 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7370            4 : 
    7371            4 :         let mut lsn = Lsn(0x10);
    7372            4 : 
    7373            4 :         #[allow(clippy::needless_range_loop)]
    7374          204 :         for idx in 0..NUM_TLINES {
    7375          200 :             let new_tline_id = TimelineId::generate();
    7376          200 :             tenant
    7377          200 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7378          200 :                 .await?;
    7379          200 :             tline = tenant
    7380          200 :                 .get_timeline(new_tline_id, true)
    7381          200 :                 .expect("Should have the branched timeline");
    7382            4 : 
    7383        20200 :             for _ in 0..NUM_KEYS {
    7384        20000 :                 lsn = Lsn(lsn.0 + 0x10);
    7385        20000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7386        20000 :                 test_key.field6 = blknum as u32;
    7387        20000 :                 let mut writer = tline.writer().await;
    7388        20000 :                 writer
    7389        20000 :                     .put(
    7390        20000 :                         test_key,
    7391        20000 :                         lsn,
    7392        20000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7393        20000 :                         &ctx,
    7394        20000 :                     )
    7395        20000 :                     .await?;
    7396        20000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7397        20000 :                 writer.finish_write(lsn);
    7398        20000 :                 drop(writer);
    7399        20000 :                 updated[idx][blknum] = lsn;
    7400            4 :             }
    7401            4 :         }
    7402            4 : 
    7403            4 :         // Read pages from leaf timeline across all ancestors.
    7404          200 :         for (idx, lsns) in updated.iter().enumerate() {
    7405        20000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7406            4 :                 // Skip empty mutations.
    7407        20000 :                 if lsn.0 == 0 {
    7408         7316 :                     continue;
    7409        12684 :                 }
    7410        12684 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7411        12684 :                 test_key.field6 = blknum as u32;
    7412        12684 :                 assert_eq!(
    7413        12684 :                     tline.get(test_key, *lsn, &ctx).await?,
    7414        12684 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7415            4 :                 );
    7416            4 :             }
    7417            4 :         }
    7418            4 :         Ok(())
    7419            4 :     }
    7420              : 
    7421              :     #[tokio::test]
    7422            4 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7423            4 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7424            4 :             .await?
    7425            4 :             .load()
    7426            4 :             .await;
    7427            4 : 
    7428            4 :         let initdb_lsn = Lsn(0x20);
    7429            4 :         let utline = tenant
    7430            4 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7431            4 :             .await?;
    7432            4 :         let tline = utline.raw_timeline().unwrap();
    7433            4 : 
    7434            4 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7435            4 :         tline.maybe_spawn_flush_loop();
    7436            4 : 
    7437            4 :         // Make sure the timeline has the minimum set of required keys for operation.
    7438            4 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7439            4 :         // Except if you `put` at `initdb_lsn`.
    7440            4 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7441            4 :         // It uses `repartition()`, which assumes some keys to be present.
    7442            4 :         // Let's make sure the test timeline can handle that case.
    7443            4 :         {
    7444            4 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7445            4 :             assert_eq!(
    7446            4 :                 timeline::FlushLoopState::Running {
    7447            4 :                     expect_initdb_optimization: false,
    7448            4 :                     initdb_optimization_count: 0,
    7449            4 :                 },
    7450            4 :                 *state
    7451            4 :             );
    7452            4 :             *state = timeline::FlushLoopState::Running {
    7453            4 :                 expect_initdb_optimization: true,
    7454            4 :                 initdb_optimization_count: 0,
    7455            4 :             };
    7456            4 :         }
    7457            4 : 
    7458            4 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7459            4 :         // As explained above, the optimization requires some keys to be present.
    7460            4 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7461            4 :         // This is what `create_test_timeline` does, by the way.
    7462            4 :         let mut modification = tline.begin_modification(initdb_lsn);
    7463            4 :         modification
    7464            4 :             .init_empty_test_timeline()
    7465            4 :             .context("init_empty_test_timeline")?;
    7466            4 :         modification
    7467            4 :             .commit(&ctx)
    7468            4 :             .await
    7469            4 :             .context("commit init_empty_test_timeline modification")?;
    7470            4 : 
    7471            4 :         // Do the flush. The flush code will check the expectations that we set above.
    7472            4 :         tline.freeze_and_flush().await?;
    7473            4 : 
    7474            4 :         // assert freeze_and_flush exercised the initdb optimization
    7475            4 :         {
    7476            4 :             let state = tline.flush_loop_state.lock().unwrap();
    7477            4 :             let timeline::FlushLoopState::Running {
    7478            4 :                 expect_initdb_optimization,
    7479            4 :                 initdb_optimization_count,
    7480            4 :             } = *state
    7481            4 :             else {
    7482            4 :                 panic!("unexpected state: {:?}", *state);
    7483            4 :             };
    7484            4 :             assert!(expect_initdb_optimization);
    7485            4 :             assert!(initdb_optimization_count > 0);
    7486            4 :         }
    7487            4 :         Ok(())
    7488            4 :     }
    7489              : 
    7490              :     #[tokio::test]
    7491            4 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7492            4 :         let name = "test_create_guard_crash";
    7493            4 :         let harness = TenantHarness::create(name).await?;
    7494            4 :         {
    7495            4 :             let (tenant, ctx) = harness.load().await;
    7496            4 :             let tline = tenant
    7497            4 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7498            4 :                 .await?;
    7499            4 :             // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
    7500            4 :             let raw_tline = tline.raw_timeline().unwrap();
    7501            4 :             raw_tline
    7502            4 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7503            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))
    7504            4 :                 .await;
    7505            4 :             std::mem::forget(tline);
    7506            4 :         }
    7507            4 : 
    7508            4 :         let (tenant, _) = harness.load().await;
    7509            4 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7510            4 :             Ok(_) => panic!("timeline should've been removed during load"),
    7511            4 :             Err(e) => {
    7512            4 :                 assert_eq!(
    7513            4 :                     e,
    7514            4 :                     GetTimelineError::NotFound {
    7515            4 :                         tenant_id: tenant.tenant_shard_id,
    7516            4 :                         timeline_id: TIMELINE_ID,
    7517            4 :                     }
    7518            4 :                 )
    7519            4 :             }
    7520            4 :         }
    7521            4 : 
    7522            4 :         assert!(
    7523            4 :             !harness
    7524            4 :                 .conf
    7525            4 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7526            4 :                 .exists()
    7527            4 :         );
    7528            4 : 
    7529            4 :         Ok(())
    7530            4 :     }
    7531              : 
    7532              :     #[tokio::test]
    7533            4 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7534            4 :         let names_algorithms = [
    7535            4 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7536            4 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7537            4 :         ];
    7538           12 :         for (name, algorithm) in names_algorithms {
    7539            8 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7540            4 :         }
    7541            4 :         Ok(())
    7542            4 :     }
    7543              : 
    7544            8 :     async fn test_read_at_max_lsn_algorithm(
    7545            8 :         name: &'static str,
    7546            8 :         compaction_algorithm: CompactionAlgorithm,
    7547            8 :     ) -> anyhow::Result<()> {
    7548            8 :         let mut harness = TenantHarness::create(name).await?;
    7549            8 :         harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
    7550            8 :             kind: compaction_algorithm,
    7551            8 :         };
    7552            8 :         let (tenant, ctx) = harness.load().await;
    7553            8 :         let tline = tenant
    7554            8 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7555            8 :             .await?;
    7556              : 
    7557            8 :         let lsn = Lsn(0x10);
    7558            8 :         let compact = false;
    7559            8 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7560              : 
    7561            8 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7562            8 :         let read_lsn = Lsn(u64::MAX - 1);
    7563              : 
    7564            8 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7565            8 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7566              : 
    7567            8 :         Ok(())
    7568            8 :     }
    7569              : 
    7570              :     #[tokio::test]
    7571            4 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7572            4 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7573            4 :         let (tenant, ctx) = harness.load().await;
    7574            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7575            4 :         let tline = tenant
    7576            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7577            4 :             .await?;
    7578            4 : 
    7579            4 :         const NUM_KEYS: usize = 1000;
    7580            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7581            4 : 
    7582            4 :         let cancel = CancellationToken::new();
    7583            4 : 
    7584            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7585            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7586            4 :         let mut test_key = base_key;
    7587            4 : 
    7588            4 :         // Track when each page was last modified. Used to assert that
    7589            4 :         // a read sees the latest page version.
    7590            4 :         let mut updated = [Lsn(0); NUM_KEYS];
    7591            4 : 
    7592            4 :         let mut lsn = Lsn(0x10);
    7593            4 :         #[allow(clippy::needless_range_loop)]
    7594         4004 :         for blknum in 0..NUM_KEYS {
    7595         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7596         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7597         4000 :             let mut writer = tline.writer().await;
    7598         4000 :             writer
    7599         4000 :                 .put(
    7600         4000 :                     test_key,
    7601         4000 :                     lsn,
    7602         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7603         4000 :                     &ctx,
    7604         4000 :                 )
    7605         4000 :                 .await?;
    7606         4000 :             writer.finish_write(lsn);
    7607         4000 :             updated[blknum] = lsn;
    7608         4000 :             drop(writer);
    7609            4 :         }
    7610            4 : 
    7611            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7612            4 : 
    7613           48 :         for iter in 0..=10 {
    7614            4 :             // Read all the blocks
    7615        44000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7616        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7617        44000 :                 assert_eq!(
    7618        44000 :                     tline.get(test_key, lsn, &ctx).await?,
    7619        44000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7620            4 :                 );
    7621            4 :             }
    7622            4 : 
    7623           44 :             let mut cnt = 0;
    7624        44000 :             for (key, value) in tline
    7625           44 :                 .get_vectored_impl(
    7626           44 :                     keyspace.clone(),
    7627           44 :                     lsn,
    7628           44 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7629           44 :                     &ctx,
    7630           44 :                 )
    7631           44 :                 .await?
    7632            4 :             {
    7633        44000 :                 let blknum = key.field6 as usize;
    7634        44000 :                 let value = value?;
    7635        44000 :                 assert!(blknum % STEP == 0);
    7636        44000 :                 let blknum = blknum / STEP;
    7637        44000 :                 assert_eq!(
    7638        44000 :                     value,
    7639        44000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    7640        44000 :                 );
    7641        44000 :                 cnt += 1;
    7642            4 :             }
    7643            4 : 
    7644           44 :             assert_eq!(cnt, NUM_KEYS);
    7645            4 : 
    7646        44044 :             for _ in 0..NUM_KEYS {
    7647        44000 :                 lsn = Lsn(lsn.0 + 0x10);
    7648        44000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7649        44000 :                 test_key.field6 = (blknum * STEP) as u32;
    7650        44000 :                 let mut writer = tline.writer().await;
    7651        44000 :                 writer
    7652        44000 :                     .put(
    7653        44000 :                         test_key,
    7654        44000 :                         lsn,
    7655        44000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7656        44000 :                         &ctx,
    7657        44000 :                     )
    7658        44000 :                     .await?;
    7659        44000 :                 writer.finish_write(lsn);
    7660        44000 :                 drop(writer);
    7661        44000 :                 updated[blknum] = lsn;
    7662            4 :             }
    7663            4 : 
    7664            4 :             // Perform two cycles of flush, compact, and GC
    7665          132 :             for round in 0..2 {
    7666           88 :                 tline.freeze_and_flush().await?;
    7667           88 :                 tline
    7668           88 :                     .compact(
    7669           88 :                         &cancel,
    7670           88 :                         if iter % 5 == 0 && round == 0 {
    7671           12 :                             let mut flags = EnumSet::new();
    7672           12 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7673           12 :                             flags.insert(CompactFlags::ForceRepartition);
    7674           12 :                             flags
    7675            4 :                         } else {
    7676           76 :                             EnumSet::empty()
    7677            4 :                         },
    7678           88 :                         &ctx,
    7679           88 :                     )
    7680           88 :                     .await?;
    7681           88 :                 tenant
    7682           88 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7683           88 :                     .await?;
    7684            4 :             }
    7685            4 :         }
    7686            4 : 
    7687            4 :         Ok(())
    7688            4 :     }
    7689              : 
    7690              :     #[tokio::test]
    7691            4 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    7692            4 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    7693            4 :         let (tenant, ctx) = harness.load().await;
    7694            4 :         let tline = tenant
    7695            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7696            4 :             .await?;
    7697            4 : 
    7698            4 :         let cancel = CancellationToken::new();
    7699            4 : 
    7700            4 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7701            4 :         base_key.field1 = AUX_KEY_PREFIX;
    7702            4 :         let test_key = base_key;
    7703            4 :         let mut lsn = Lsn(0x10);
    7704            4 : 
    7705           84 :         for _ in 0..20 {
    7706           80 :             lsn = Lsn(lsn.0 + 0x10);
    7707           80 :             let mut writer = tline.writer().await;
    7708           80 :             writer
    7709           80 :                 .put(
    7710           80 :                     test_key,
    7711           80 :                     lsn,
    7712           80 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    7713           80 :                     &ctx,
    7714           80 :                 )
    7715           80 :                 .await?;
    7716           80 :             writer.finish_write(lsn);
    7717           80 :             drop(writer);
    7718           80 :             tline.freeze_and_flush().await?; // force create a delta layer
    7719            4 :         }
    7720            4 : 
    7721            4 :         let before_num_l0_delta_files =
    7722            4 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    7723            4 : 
    7724            4 :         tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
    7725            4 : 
    7726            4 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    7727            4 : 
    7728            4 :         assert!(
    7729            4 :             after_num_l0_delta_files < before_num_l0_delta_files,
    7730            4 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    7731            4 :         );
    7732            4 : 
    7733            4 :         assert_eq!(
    7734            4 :             tline.get(test_key, lsn, &ctx).await?,
    7735            4 :             test_img(&format!("{} at {}", 0, lsn))
    7736            4 :         );
    7737            4 : 
    7738            4 :         Ok(())
    7739            4 :     }
    7740              : 
    7741              :     #[tokio::test]
    7742            4 :     async fn test_aux_file_e2e() {
    7743            4 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    7744            4 : 
    7745            4 :         let (tenant, ctx) = harness.load().await;
    7746            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7747            4 : 
    7748            4 :         let mut lsn = Lsn(0x08);
    7749            4 : 
    7750            4 :         let tline: Arc<Timeline> = tenant
    7751            4 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    7752            4 :             .await
    7753            4 :             .unwrap();
    7754            4 : 
    7755            4 :         {
    7756            4 :             lsn += 8;
    7757            4 :             let mut modification = tline.begin_modification(lsn);
    7758            4 :             modification
    7759            4 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    7760            4 :                 .await
    7761            4 :                 .unwrap();
    7762            4 :             modification.commit(&ctx).await.unwrap();
    7763            4 :         }
    7764            4 : 
    7765            4 :         // we can read everything from the storage
    7766            4 :         let files = tline
    7767            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7768            4 :             .await
    7769            4 :             .unwrap();
    7770            4 :         assert_eq!(
    7771            4 :             files.get("pg_logical/mappings/test1"),
    7772            4 :             Some(&bytes::Bytes::from_static(b"first"))
    7773            4 :         );
    7774            4 : 
    7775            4 :         {
    7776            4 :             lsn += 8;
    7777            4 :             let mut modification = tline.begin_modification(lsn);
    7778            4 :             modification
    7779            4 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    7780            4 :                 .await
    7781            4 :                 .unwrap();
    7782            4 :             modification.commit(&ctx).await.unwrap();
    7783            4 :         }
    7784            4 : 
    7785            4 :         let files = tline
    7786            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7787            4 :             .await
    7788            4 :             .unwrap();
    7789            4 :         assert_eq!(
    7790            4 :             files.get("pg_logical/mappings/test2"),
    7791            4 :             Some(&bytes::Bytes::from_static(b"second"))
    7792            4 :         );
    7793            4 : 
    7794            4 :         let child = tenant
    7795            4 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    7796            4 :             .await
    7797            4 :             .unwrap();
    7798            4 : 
    7799            4 :         let files = child
    7800            4 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    7801            4 :             .await
    7802            4 :             .unwrap();
    7803            4 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    7804            4 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    7805            4 :     }
    7806              : 
    7807              :     #[tokio::test]
    7808            4 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    7809            4 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    7810            4 :         let (tenant, ctx) = harness.load().await;
    7811            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7812            4 :         let tline = tenant
    7813            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7814            4 :             .await?;
    7815            4 : 
    7816            4 :         const NUM_KEYS: usize = 1000;
    7817            4 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7818            4 : 
    7819            4 :         let cancel = CancellationToken::new();
    7820            4 : 
    7821            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7822            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    7823            4 :         let mut test_key = base_key;
    7824            4 :         let mut lsn = Lsn(0x10);
    7825            4 : 
    7826           16 :         async fn scan_with_statistics(
    7827           16 :             tline: &Timeline,
    7828           16 :             keyspace: &KeySpace,
    7829           16 :             lsn: Lsn,
    7830           16 :             ctx: &RequestContext,
    7831           16 :             io_concurrency: IoConcurrency,
    7832           16 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    7833           16 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    7834           16 :             let res = tline
    7835           16 :                 .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
    7836           16 :                 .await?;
    7837           16 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    7838           16 :         }
    7839            4 : 
    7840            4 :         #[allow(clippy::needless_range_loop)]
    7841         4004 :         for blknum in 0..NUM_KEYS {
    7842         4000 :             lsn = Lsn(lsn.0 + 0x10);
    7843         4000 :             test_key.field6 = (blknum * STEP) as u32;
    7844         4000 :             let mut writer = tline.writer().await;
    7845         4000 :             writer
    7846         4000 :                 .put(
    7847         4000 :                     test_key,
    7848         4000 :                     lsn,
    7849         4000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7850         4000 :                     &ctx,
    7851         4000 :                 )
    7852         4000 :                 .await?;
    7853         4000 :             writer.finish_write(lsn);
    7854         4000 :             drop(writer);
    7855            4 :         }
    7856            4 : 
    7857            4 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7858            4 : 
    7859           44 :         for iter in 1..=10 {
    7860        40040 :             for _ in 0..NUM_KEYS {
    7861        40000 :                 lsn = Lsn(lsn.0 + 0x10);
    7862        40000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7863        40000 :                 test_key.field6 = (blknum * STEP) as u32;
    7864        40000 :                 let mut writer = tline.writer().await;
    7865        40000 :                 writer
    7866        40000 :                     .put(
    7867        40000 :                         test_key,
    7868        40000 :                         lsn,
    7869        40000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7870        40000 :                         &ctx,
    7871        40000 :                     )
    7872        40000 :                     .await?;
    7873        40000 :                 writer.finish_write(lsn);
    7874        40000 :                 drop(writer);
    7875            4 :             }
    7876            4 : 
    7877           40 :             tline.freeze_and_flush().await?;
    7878            4 : 
    7879           40 :             if iter % 5 == 0 {
    7880            8 :                 let (_, before_delta_file_accessed) =
    7881            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7882            8 :                         .await?;
    7883            8 :                 tline
    7884            8 :                     .compact(
    7885            8 :                         &cancel,
    7886            8 :                         {
    7887            8 :                             let mut flags = EnumSet::new();
    7888            8 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    7889            8 :                             flags.insert(CompactFlags::ForceRepartition);
    7890            8 :                             flags
    7891            8 :                         },
    7892            8 :                         &ctx,
    7893            8 :                     )
    7894            8 :                     .await?;
    7895            8 :                 let (_, after_delta_file_accessed) =
    7896            8 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    7897            8 :                         .await?;
    7898            8 :                 assert!(
    7899            8 :                     after_delta_file_accessed < before_delta_file_accessed,
    7900            4 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    7901            4 :                 );
    7902            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.
    7903            8 :                 assert!(
    7904            8 :                     after_delta_file_accessed <= 2,
    7905            4 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    7906            4 :                 );
    7907           32 :             }
    7908            4 :         }
    7909            4 : 
    7910            4 :         Ok(())
    7911            4 :     }
    7912              : 
    7913              :     #[tokio::test]
    7914            4 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    7915            4 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    7916            4 :         let (tenant, ctx) = harness.load().await;
    7917            4 : 
    7918            4 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7919            4 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    7920            4 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    7921            4 : 
    7922            4 :         let tline = tenant
    7923            4 :             .create_test_timeline_with_layers(
    7924            4 :                 TIMELINE_ID,
    7925            4 :                 Lsn(0x10),
    7926            4 :                 DEFAULT_PG_VERSION,
    7927            4 :                 &ctx,
    7928            4 :                 Vec::new(), // delta layers
    7929            4 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    7930            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
    7931            4 :             )
    7932            4 :             .await?;
    7933            4 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    7934            4 : 
    7935            4 :         let child = tenant
    7936            4 :             .branch_timeline_test_with_layers(
    7937            4 :                 &tline,
    7938            4 :                 NEW_TIMELINE_ID,
    7939            4 :                 Some(Lsn(0x20)),
    7940            4 :                 &ctx,
    7941            4 :                 Vec::new(), // delta layers
    7942            4 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    7943            4 :                 Lsn(0x30),
    7944            4 :             )
    7945            4 :             .await
    7946            4 :             .unwrap();
    7947            4 : 
    7948            4 :         let lsn = Lsn(0x30);
    7949            4 : 
    7950            4 :         // test vectored get on parent timeline
    7951            4 :         assert_eq!(
    7952            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    7953            4 :             Some(test_img("data key 1"))
    7954            4 :         );
    7955            4 :         assert!(
    7956            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    7957            4 :                 .await
    7958            4 :                 .unwrap_err()
    7959            4 :                 .is_missing_key_error()
    7960            4 :         );
    7961            4 :         assert!(
    7962            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    7963            4 :                 .await
    7964            4 :                 .unwrap_err()
    7965            4 :                 .is_missing_key_error()
    7966            4 :         );
    7967            4 : 
    7968            4 :         // test vectored get on child timeline
    7969            4 :         assert_eq!(
    7970            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    7971            4 :             Some(test_img("data key 1"))
    7972            4 :         );
    7973            4 :         assert_eq!(
    7974            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    7975            4 :             Some(test_img("data key 2"))
    7976            4 :         );
    7977            4 :         assert!(
    7978            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    7979            4 :                 .await
    7980            4 :                 .unwrap_err()
    7981            4 :                 .is_missing_key_error()
    7982            4 :         );
    7983            4 : 
    7984            4 :         Ok(())
    7985            4 :     }
    7986              : 
    7987              :     #[tokio::test]
    7988            4 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    7989            4 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    7990            4 :         let (tenant, ctx) = harness.load().await;
    7991            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7992            4 : 
    7993            4 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    7994            4 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    7995            4 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    7996            4 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    7997            4 : 
    7998            4 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    7999            4 :         let base_inherited_key_child =
    8000            4 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8001            4 :         let base_inherited_key_nonexist =
    8002            4 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8003            4 :         let base_inherited_key_overwrite =
    8004            4 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8005            4 : 
    8006            4 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8007            4 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8008            4 : 
    8009            4 :         let tline = tenant
    8010            4 :             .create_test_timeline_with_layers(
    8011            4 :                 TIMELINE_ID,
    8012            4 :                 Lsn(0x10),
    8013            4 :                 DEFAULT_PG_VERSION,
    8014            4 :                 &ctx,
    8015            4 :                 Vec::new(), // delta layers
    8016            4 :                 vec![(
    8017            4 :                     Lsn(0x20),
    8018            4 :                     vec![
    8019            4 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8020            4 :                         (
    8021            4 :                             base_inherited_key_overwrite,
    8022            4 :                             test_img("metadata key overwrite 1a"),
    8023            4 :                         ),
    8024            4 :                         (base_key, test_img("metadata key 1")),
    8025            4 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8026            4 :                     ],
    8027            4 :                 )], // image layers
    8028            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
    8029            4 :             )
    8030            4 :             .await?;
    8031            4 : 
    8032            4 :         let child = tenant
    8033            4 :             .branch_timeline_test_with_layers(
    8034            4 :                 &tline,
    8035            4 :                 NEW_TIMELINE_ID,
    8036            4 :                 Some(Lsn(0x20)),
    8037            4 :                 &ctx,
    8038            4 :                 Vec::new(), // delta layers
    8039            4 :                 vec![(
    8040            4 :                     Lsn(0x30),
    8041            4 :                     vec![
    8042            4 :                         (
    8043            4 :                             base_inherited_key_child,
    8044            4 :                             test_img("metadata inherited key 2"),
    8045            4 :                         ),
    8046            4 :                         (
    8047            4 :                             base_inherited_key_overwrite,
    8048            4 :                             test_img("metadata key overwrite 2a"),
    8049            4 :                         ),
    8050            4 :                         (base_key_child, test_img("metadata key 2")),
    8051            4 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8052            4 :                     ],
    8053            4 :                 )], // image layers
    8054            4 :                 Lsn(0x30),
    8055            4 :             )
    8056            4 :             .await
    8057            4 :             .unwrap();
    8058            4 : 
    8059            4 :         let lsn = Lsn(0x30);
    8060            4 : 
    8061            4 :         // test vectored get on parent timeline
    8062            4 :         assert_eq!(
    8063            4 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8064            4 :             Some(test_img("metadata key 1"))
    8065            4 :         );
    8066            4 :         assert_eq!(
    8067            4 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8068            4 :             None
    8069            4 :         );
    8070            4 :         assert_eq!(
    8071            4 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8072            4 :             None
    8073            4 :         );
    8074            4 :         assert_eq!(
    8075            4 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8076            4 :             Some(test_img("metadata key overwrite 1b"))
    8077            4 :         );
    8078            4 :         assert_eq!(
    8079            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8080            4 :             Some(test_img("metadata inherited key 1"))
    8081            4 :         );
    8082            4 :         assert_eq!(
    8083            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8084            4 :             None
    8085            4 :         );
    8086            4 :         assert_eq!(
    8087            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8088            4 :             None
    8089            4 :         );
    8090            4 :         assert_eq!(
    8091            4 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8092            4 :             Some(test_img("metadata key overwrite 1a"))
    8093            4 :         );
    8094            4 : 
    8095            4 :         // test vectored get on child timeline
    8096            4 :         assert_eq!(
    8097            4 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8098            4 :             None
    8099            4 :         );
    8100            4 :         assert_eq!(
    8101            4 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8102            4 :             Some(test_img("metadata key 2"))
    8103            4 :         );
    8104            4 :         assert_eq!(
    8105            4 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8106            4 :             None
    8107            4 :         );
    8108            4 :         assert_eq!(
    8109            4 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8110            4 :             Some(test_img("metadata inherited key 1"))
    8111            4 :         );
    8112            4 :         assert_eq!(
    8113            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8114            4 :             Some(test_img("metadata inherited key 2"))
    8115            4 :         );
    8116            4 :         assert_eq!(
    8117            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8118            4 :             None
    8119            4 :         );
    8120            4 :         assert_eq!(
    8121            4 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8122            4 :             Some(test_img("metadata key overwrite 2b"))
    8123            4 :         );
    8124            4 :         assert_eq!(
    8125            4 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8126            4 :             Some(test_img("metadata key overwrite 2a"))
    8127            4 :         );
    8128            4 : 
    8129            4 :         // test vectored scan on parent timeline
    8130            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8131            4 :         let res = tline
    8132            4 :             .get_vectored_impl(
    8133            4 :                 KeySpace::single(Key::metadata_key_range()),
    8134            4 :                 lsn,
    8135            4 :                 &mut reconstruct_state,
    8136            4 :                 &ctx,
    8137            4 :             )
    8138            4 :             .await?;
    8139            4 : 
    8140            4 :         assert_eq!(
    8141            4 :             res.into_iter()
    8142           16 :                 .map(|(k, v)| (k, v.unwrap()))
    8143            4 :                 .collect::<Vec<_>>(),
    8144            4 :             vec![
    8145            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8146            4 :                 (
    8147            4 :                     base_inherited_key_overwrite,
    8148            4 :                     test_img("metadata key overwrite 1a")
    8149            4 :                 ),
    8150            4 :                 (base_key, test_img("metadata key 1")),
    8151            4 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8152            4 :             ]
    8153            4 :         );
    8154            4 : 
    8155            4 :         // test vectored scan on child timeline
    8156            4 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8157            4 :         let res = child
    8158            4 :             .get_vectored_impl(
    8159            4 :                 KeySpace::single(Key::metadata_key_range()),
    8160            4 :                 lsn,
    8161            4 :                 &mut reconstruct_state,
    8162            4 :                 &ctx,
    8163            4 :             )
    8164            4 :             .await?;
    8165            4 : 
    8166            4 :         assert_eq!(
    8167            4 :             res.into_iter()
    8168           20 :                 .map(|(k, v)| (k, v.unwrap()))
    8169            4 :                 .collect::<Vec<_>>(),
    8170            4 :             vec![
    8171            4 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8172            4 :                 (
    8173            4 :                     base_inherited_key_child,
    8174            4 :                     test_img("metadata inherited key 2")
    8175            4 :                 ),
    8176            4 :                 (
    8177            4 :                     base_inherited_key_overwrite,
    8178            4 :                     test_img("metadata key overwrite 2a")
    8179            4 :                 ),
    8180            4 :                 (base_key_child, test_img("metadata key 2")),
    8181            4 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8182            4 :             ]
    8183            4 :         );
    8184            4 : 
    8185            4 :         Ok(())
    8186            4 :     }
    8187              : 
    8188          112 :     async fn get_vectored_impl_wrapper(
    8189          112 :         tline: &Arc<Timeline>,
    8190          112 :         key: Key,
    8191          112 :         lsn: Lsn,
    8192          112 :         ctx: &RequestContext,
    8193          112 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8194          112 :         let io_concurrency =
    8195          112 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    8196          112 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8197          112 :         let mut res = tline
    8198          112 :             .get_vectored_impl(
    8199          112 :                 KeySpace::single(key..key.next()),
    8200          112 :                 lsn,
    8201          112 :                 &mut reconstruct_state,
    8202          112 :                 ctx,
    8203          112 :             )
    8204          112 :             .await?;
    8205          100 :         Ok(res.pop_last().map(|(k, v)| {
    8206           64 :             assert_eq!(k, key);
    8207           64 :             v.unwrap()
    8208          100 :         }))
    8209          112 :     }
    8210              : 
    8211              :     #[tokio::test]
    8212            4 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8213            4 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8214            4 :         let (tenant, ctx) = harness.load().await;
    8215            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8216            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8217            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8218            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8219            4 : 
    8220            4 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8221            4 :         // Lsn 0x30 key0, key3, no key1+key2
    8222            4 :         // Lsn 0x20 key1+key2 tomestones
    8223            4 :         // Lsn 0x10 key1 in image, key2 in delta
    8224            4 :         let tline = tenant
    8225            4 :             .create_test_timeline_with_layers(
    8226            4 :                 TIMELINE_ID,
    8227            4 :                 Lsn(0x10),
    8228            4 :                 DEFAULT_PG_VERSION,
    8229            4 :                 &ctx,
    8230            4 :                 // delta layers
    8231            4 :                 vec![
    8232            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8233            4 :                         Lsn(0x10)..Lsn(0x20),
    8234            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8235            4 :                     ),
    8236            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8237            4 :                         Lsn(0x20)..Lsn(0x30),
    8238            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8239            4 :                     ),
    8240            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8241            4 :                         Lsn(0x20)..Lsn(0x30),
    8242            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8243            4 :                     ),
    8244            4 :                 ],
    8245            4 :                 // image layers
    8246            4 :                 vec![
    8247            4 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8248            4 :                     (
    8249            4 :                         Lsn(0x30),
    8250            4 :                         vec![
    8251            4 :                             (key0, test_img("metadata key 0")),
    8252            4 :                             (key3, test_img("metadata key 3")),
    8253            4 :                         ],
    8254            4 :                     ),
    8255            4 :                 ],
    8256            4 :                 Lsn(0x30),
    8257            4 :             )
    8258            4 :             .await?;
    8259            4 : 
    8260            4 :         let lsn = Lsn(0x30);
    8261            4 :         let old_lsn = Lsn(0x20);
    8262            4 : 
    8263            4 :         assert_eq!(
    8264            4 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8265            4 :             Some(test_img("metadata key 0"))
    8266            4 :         );
    8267            4 :         assert_eq!(
    8268            4 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8269            4 :             None,
    8270            4 :         );
    8271            4 :         assert_eq!(
    8272            4 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8273            4 :             None,
    8274            4 :         );
    8275            4 :         assert_eq!(
    8276            4 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8277            4 :             Some(Bytes::new()),
    8278            4 :         );
    8279            4 :         assert_eq!(
    8280            4 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8281            4 :             Some(Bytes::new()),
    8282            4 :         );
    8283            4 :         assert_eq!(
    8284            4 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8285            4 :             Some(test_img("metadata key 3"))
    8286            4 :         );
    8287            4 : 
    8288            4 :         Ok(())
    8289            4 :     }
    8290              : 
    8291              :     #[tokio::test]
    8292            4 :     async fn test_metadata_tombstone_image_creation() {
    8293            4 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8294            4 :             .await
    8295            4 :             .unwrap();
    8296            4 :         let (tenant, ctx) = harness.load().await;
    8297            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8298            4 : 
    8299            4 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8300            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8301            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8302            4 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8303            4 : 
    8304            4 :         let tline = tenant
    8305            4 :             .create_test_timeline_with_layers(
    8306            4 :                 TIMELINE_ID,
    8307            4 :                 Lsn(0x10),
    8308            4 :                 DEFAULT_PG_VERSION,
    8309            4 :                 &ctx,
    8310            4 :                 // delta layers
    8311            4 :                 vec![
    8312            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8313            4 :                         Lsn(0x10)..Lsn(0x20),
    8314            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8315            4 :                     ),
    8316            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8317            4 :                         Lsn(0x20)..Lsn(0x30),
    8318            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8319            4 :                     ),
    8320            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8321            4 :                         Lsn(0x20)..Lsn(0x30),
    8322            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8323            4 :                     ),
    8324            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8325            4 :                         Lsn(0x30)..Lsn(0x40),
    8326            4 :                         vec![
    8327            4 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8328            4 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8329            4 :                         ],
    8330            4 :                     ),
    8331            4 :                 ],
    8332            4 :                 // image layers
    8333            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8334            4 :                 Lsn(0x40),
    8335            4 :             )
    8336            4 :             .await
    8337            4 :             .unwrap();
    8338            4 : 
    8339            4 :         let cancel = CancellationToken::new();
    8340            4 : 
    8341            4 :         tline
    8342            4 :             .compact(
    8343            4 :                 &cancel,
    8344            4 :                 {
    8345            4 :                     let mut flags = EnumSet::new();
    8346            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8347            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8348            4 :                     flags
    8349            4 :                 },
    8350            4 :                 &ctx,
    8351            4 :             )
    8352            4 :             .await
    8353            4 :             .unwrap();
    8354            4 : 
    8355            4 :         // Image layers are created at last_record_lsn
    8356            4 :         let images = tline
    8357            4 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8358            4 :             .await
    8359            4 :             .unwrap()
    8360            4 :             .into_iter()
    8361           36 :             .filter(|(k, _)| k.is_metadata_key())
    8362            4 :             .collect::<Vec<_>>();
    8363            4 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8364            4 :     }
    8365              : 
    8366              :     #[tokio::test]
    8367            4 :     async fn test_metadata_tombstone_empty_image_creation() {
    8368            4 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8369            4 :             .await
    8370            4 :             .unwrap();
    8371            4 :         let (tenant, ctx) = harness.load().await;
    8372            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8373            4 : 
    8374            4 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8375            4 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8376            4 : 
    8377            4 :         let tline = tenant
    8378            4 :             .create_test_timeline_with_layers(
    8379            4 :                 TIMELINE_ID,
    8380            4 :                 Lsn(0x10),
    8381            4 :                 DEFAULT_PG_VERSION,
    8382            4 :                 &ctx,
    8383            4 :                 // delta layers
    8384            4 :                 vec![
    8385            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8386            4 :                         Lsn(0x10)..Lsn(0x20),
    8387            4 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8388            4 :                     ),
    8389            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8390            4 :                         Lsn(0x20)..Lsn(0x30),
    8391            4 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8392            4 :                     ),
    8393            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8394            4 :                         Lsn(0x20)..Lsn(0x30),
    8395            4 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8396            4 :                     ),
    8397            4 :                 ],
    8398            4 :                 // image layers
    8399            4 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8400            4 :                 Lsn(0x30),
    8401            4 :             )
    8402            4 :             .await
    8403            4 :             .unwrap();
    8404            4 : 
    8405            4 :         let cancel = CancellationToken::new();
    8406            4 : 
    8407            4 :         tline
    8408            4 :             .compact(
    8409            4 :                 &cancel,
    8410            4 :                 {
    8411            4 :                     let mut flags = EnumSet::new();
    8412            4 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8413            4 :                     flags.insert(CompactFlags::ForceRepartition);
    8414            4 :                     flags
    8415            4 :                 },
    8416            4 :                 &ctx,
    8417            4 :             )
    8418            4 :             .await
    8419            4 :             .unwrap();
    8420            4 : 
    8421            4 :         // Image layers are created at last_record_lsn
    8422            4 :         let images = tline
    8423            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8424            4 :             .await
    8425            4 :             .unwrap()
    8426            4 :             .into_iter()
    8427           28 :             .filter(|(k, _)| k.is_metadata_key())
    8428            4 :             .collect::<Vec<_>>();
    8429            4 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8430            4 :     }
    8431              : 
    8432              :     #[tokio::test]
    8433            4 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8434            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8435            4 :         let (tenant, ctx) = harness.load().await;
    8436            4 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8437            4 : 
    8438          204 :         fn get_key(id: u32) -> Key {
    8439          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8440          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8441          204 :             key.field6 = id;
    8442          204 :             key
    8443          204 :         }
    8444            4 : 
    8445            4 :         // We create
    8446            4 :         // - one bottom-most image layer,
    8447            4 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8448            4 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8449            4 :         // - a delta layer D3 above the horizon.
    8450            4 :         //
    8451            4 :         //                             | D3 |
    8452            4 :         //  | D1 |
    8453            4 :         // -|    |-- gc horizon -----------------
    8454            4 :         //  |    |                | D2 |
    8455            4 :         // --------- img layer ------------------
    8456            4 :         //
    8457            4 :         // What we should expact from this compaction is:
    8458            4 :         //                             | D3 |
    8459            4 :         //  | Part of D1 |
    8460            4 :         // --------- img layer with D1+D2 at GC horizon------------------
    8461            4 : 
    8462            4 :         // img layer at 0x10
    8463            4 :         let img_layer = (0..10)
    8464           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8465            4 :             .collect_vec();
    8466            4 : 
    8467            4 :         let delta1 = vec![
    8468            4 :             (
    8469            4 :                 get_key(1),
    8470            4 :                 Lsn(0x20),
    8471            4 :                 Value::Image(Bytes::from("value 1@0x20")),
    8472            4 :             ),
    8473            4 :             (
    8474            4 :                 get_key(2),
    8475            4 :                 Lsn(0x30),
    8476            4 :                 Value::Image(Bytes::from("value 2@0x30")),
    8477            4 :             ),
    8478            4 :             (
    8479            4 :                 get_key(3),
    8480            4 :                 Lsn(0x40),
    8481            4 :                 Value::Image(Bytes::from("value 3@0x40")),
    8482            4 :             ),
    8483            4 :         ];
    8484            4 :         let delta2 = vec![
    8485            4 :             (
    8486            4 :                 get_key(5),
    8487            4 :                 Lsn(0x20),
    8488            4 :                 Value::Image(Bytes::from("value 5@0x20")),
    8489            4 :             ),
    8490            4 :             (
    8491            4 :                 get_key(6),
    8492            4 :                 Lsn(0x20),
    8493            4 :                 Value::Image(Bytes::from("value 6@0x20")),
    8494            4 :             ),
    8495            4 :         ];
    8496            4 :         let delta3 = vec![
    8497            4 :             (
    8498            4 :                 get_key(8),
    8499            4 :                 Lsn(0x48),
    8500            4 :                 Value::Image(Bytes::from("value 8@0x48")),
    8501            4 :             ),
    8502            4 :             (
    8503            4 :                 get_key(9),
    8504            4 :                 Lsn(0x48),
    8505            4 :                 Value::Image(Bytes::from("value 9@0x48")),
    8506            4 :             ),
    8507            4 :         ];
    8508            4 : 
    8509            4 :         let tline = tenant
    8510            4 :             .create_test_timeline_with_layers(
    8511            4 :                 TIMELINE_ID,
    8512            4 :                 Lsn(0x10),
    8513            4 :                 DEFAULT_PG_VERSION,
    8514            4 :                 &ctx,
    8515            4 :                 vec![
    8516            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8517            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8518            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8519            4 :                 ], // delta layers
    8520            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8521            4 :                 Lsn(0x50),
    8522            4 :             )
    8523            4 :             .await?;
    8524            4 :         {
    8525            4 :             tline
    8526            4 :                 .applied_gc_cutoff_lsn
    8527            4 :                 .lock_for_write()
    8528            4 :                 .store_and_unlock(Lsn(0x30))
    8529            4 :                 .wait()
    8530            4 :                 .await;
    8531            4 :             // Update GC info
    8532            4 :             let mut guard = tline.gc_info.write().unwrap();
    8533            4 :             guard.cutoffs.time = Lsn(0x30);
    8534            4 :             guard.cutoffs.space = Lsn(0x30);
    8535            4 :         }
    8536            4 : 
    8537            4 :         let expected_result = [
    8538            4 :             Bytes::from_static(b"value 0@0x10"),
    8539            4 :             Bytes::from_static(b"value 1@0x20"),
    8540            4 :             Bytes::from_static(b"value 2@0x30"),
    8541            4 :             Bytes::from_static(b"value 3@0x40"),
    8542            4 :             Bytes::from_static(b"value 4@0x10"),
    8543            4 :             Bytes::from_static(b"value 5@0x20"),
    8544            4 :             Bytes::from_static(b"value 6@0x20"),
    8545            4 :             Bytes::from_static(b"value 7@0x10"),
    8546            4 :             Bytes::from_static(b"value 8@0x48"),
    8547            4 :             Bytes::from_static(b"value 9@0x48"),
    8548            4 :         ];
    8549            4 : 
    8550           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8551           40 :             assert_eq!(
    8552           40 :                 tline
    8553           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8554           40 :                     .await
    8555           40 :                     .unwrap(),
    8556            4 :                 expected
    8557            4 :             );
    8558            4 :         }
    8559            4 : 
    8560            4 :         let cancel = CancellationToken::new();
    8561            4 :         tline
    8562            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8563            4 :             .await
    8564            4 :             .unwrap();
    8565            4 : 
    8566           40 :         for (idx, expected) in expected_result.iter().enumerate() {
    8567           40 :             assert_eq!(
    8568           40 :                 tline
    8569           40 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8570           40 :                     .await
    8571           40 :                     .unwrap(),
    8572            4 :                 expected
    8573            4 :             );
    8574            4 :         }
    8575            4 : 
    8576            4 :         // Check if the image layer at the GC horizon contains exactly what we want
    8577            4 :         let image_at_gc_horizon = tline
    8578            4 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8579            4 :             .await
    8580            4 :             .unwrap()
    8581            4 :             .into_iter()
    8582           68 :             .filter(|(k, _)| k.is_metadata_key())
    8583            4 :             .collect::<Vec<_>>();
    8584            4 : 
    8585            4 :         assert_eq!(image_at_gc_horizon.len(), 10);
    8586            4 :         let expected_result = [
    8587            4 :             Bytes::from_static(b"value 0@0x10"),
    8588            4 :             Bytes::from_static(b"value 1@0x20"),
    8589            4 :             Bytes::from_static(b"value 2@0x30"),
    8590            4 :             Bytes::from_static(b"value 3@0x10"),
    8591            4 :             Bytes::from_static(b"value 4@0x10"),
    8592            4 :             Bytes::from_static(b"value 5@0x20"),
    8593            4 :             Bytes::from_static(b"value 6@0x20"),
    8594            4 :             Bytes::from_static(b"value 7@0x10"),
    8595            4 :             Bytes::from_static(b"value 8@0x10"),
    8596            4 :             Bytes::from_static(b"value 9@0x10"),
    8597            4 :         ];
    8598           44 :         for idx in 0..10 {
    8599           40 :             assert_eq!(
    8600           40 :                 image_at_gc_horizon[idx],
    8601           40 :                 (get_key(idx as u32), expected_result[idx].clone())
    8602           40 :             );
    8603            4 :         }
    8604            4 : 
    8605            4 :         // Check if old layers are removed / new layers have the expected LSN
    8606            4 :         let all_layers = inspect_and_sort(&tline, None).await;
    8607            4 :         assert_eq!(
    8608            4 :             all_layers,
    8609            4 :             vec![
    8610            4 :                 // Image layer at GC horizon
    8611            4 :                 PersistentLayerKey {
    8612            4 :                     key_range: Key::MIN..Key::MAX,
    8613            4 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    8614            4 :                     is_delta: false
    8615            4 :                 },
    8616            4 :                 // The delta layer below the horizon
    8617            4 :                 PersistentLayerKey {
    8618            4 :                     key_range: get_key(3)..get_key(4),
    8619            4 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    8620            4 :                     is_delta: true
    8621            4 :                 },
    8622            4 :                 // The delta3 layer that should not be picked for the compaction
    8623            4 :                 PersistentLayerKey {
    8624            4 :                     key_range: get_key(8)..get_key(10),
    8625            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    8626            4 :                     is_delta: true
    8627            4 :                 }
    8628            4 :             ]
    8629            4 :         );
    8630            4 : 
    8631            4 :         // increase GC horizon and compact again
    8632            4 :         {
    8633            4 :             tline
    8634            4 :                 .applied_gc_cutoff_lsn
    8635            4 :                 .lock_for_write()
    8636            4 :                 .store_and_unlock(Lsn(0x40))
    8637            4 :                 .wait()
    8638            4 :                 .await;
    8639            4 :             // Update GC info
    8640            4 :             let mut guard = tline.gc_info.write().unwrap();
    8641            4 :             guard.cutoffs.time = Lsn(0x40);
    8642            4 :             guard.cutoffs.space = Lsn(0x40);
    8643            4 :         }
    8644            4 :         tline
    8645            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8646            4 :             .await
    8647            4 :             .unwrap();
    8648            4 : 
    8649            4 :         Ok(())
    8650            4 :     }
    8651              : 
    8652              :     #[cfg(feature = "testing")]
    8653              :     #[tokio::test]
    8654            4 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    8655            4 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    8656            4 :         let (tenant, ctx) = harness.load().await;
    8657            4 : 
    8658           48 :         fn get_key(id: u32) -> Key {
    8659           48 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8660           48 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8661           48 :             key.field6 = id;
    8662           48 :             key
    8663           48 :         }
    8664            4 : 
    8665            4 :         let delta1 = vec![
    8666            4 :             (
    8667            4 :                 get_key(1),
    8668            4 :                 Lsn(0x20),
    8669            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8670            4 :             ),
    8671            4 :             (
    8672            4 :                 get_key(1),
    8673            4 :                 Lsn(0x30),
    8674            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8675            4 :             ),
    8676            4 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    8677            4 :             (
    8678            4 :                 get_key(2),
    8679            4 :                 Lsn(0x20),
    8680            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    8681            4 :             ),
    8682            4 :             (
    8683            4 :                 get_key(2),
    8684            4 :                 Lsn(0x30),
    8685            4 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    8686            4 :             ),
    8687            4 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    8688            4 :             (
    8689            4 :                 get_key(3),
    8690            4 :                 Lsn(0x20),
    8691            4 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    8692            4 :             ),
    8693            4 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    8694            4 :             (
    8695            4 :                 get_key(4),
    8696            4 :                 Lsn(0x20),
    8697            4 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    8698            4 :             ),
    8699            4 :         ];
    8700            4 :         let image1 = vec![(get_key(1), "0x10".into())];
    8701            4 : 
    8702            4 :         let tline = tenant
    8703            4 :             .create_test_timeline_with_layers(
    8704            4 :                 TIMELINE_ID,
    8705            4 :                 Lsn(0x10),
    8706            4 :                 DEFAULT_PG_VERSION,
    8707            4 :                 &ctx,
    8708            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    8709            4 :                     Lsn(0x10)..Lsn(0x40),
    8710            4 :                     delta1,
    8711            4 :                 )], // delta layers
    8712            4 :                 vec![(Lsn(0x10), image1)], // image layers
    8713            4 :                 Lsn(0x50),
    8714            4 :             )
    8715            4 :             .await?;
    8716            4 : 
    8717            4 :         assert_eq!(
    8718            4 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    8719            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8720            4 :         );
    8721            4 :         assert_eq!(
    8722            4 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    8723            4 :             Bytes::from_static(b"0x10,0x20,0x30")
    8724            4 :         );
    8725            4 : 
    8726            4 :         // Need to remove the limit of "Neon WAL redo requires base image".
    8727            4 : 
    8728            4 :         // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
    8729            4 :         // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
    8730            4 : 
    8731            4 :         Ok(())
    8732            4 :     }
    8733              : 
    8734              :     #[tokio::test(start_paused = true)]
    8735            4 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    8736            4 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    8737            4 :             .await
    8738            4 :             .unwrap()
    8739            4 :             .load()
    8740            4 :             .await;
    8741            4 :         // Advance to the lsn lease deadline so that GC is not blocked by
    8742            4 :         // initial transition into AttachedSingle.
    8743            4 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    8744            4 :         tokio::time::resume();
    8745            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8746            4 : 
    8747            4 :         let end_lsn = Lsn(0x100);
    8748            4 :         let image_layers = (0x20..=0x90)
    8749            4 :             .step_by(0x10)
    8750           32 :             .map(|n| {
    8751           32 :                 (
    8752           32 :                     Lsn(n),
    8753           32 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    8754           32 :                 )
    8755           32 :             })
    8756            4 :             .collect();
    8757            4 : 
    8758            4 :         let timeline = tenant
    8759            4 :             .create_test_timeline_with_layers(
    8760            4 :                 TIMELINE_ID,
    8761            4 :                 Lsn(0x10),
    8762            4 :                 DEFAULT_PG_VERSION,
    8763            4 :                 &ctx,
    8764            4 :                 Vec::new(),
    8765            4 :                 image_layers,
    8766            4 :                 end_lsn,
    8767            4 :             )
    8768            4 :             .await?;
    8769            4 : 
    8770            4 :         let leased_lsns = [0x30, 0x50, 0x70];
    8771            4 :         let mut leases = Vec::new();
    8772           12 :         leased_lsns.iter().for_each(|n| {
    8773           12 :             leases.push(
    8774           12 :                 timeline
    8775           12 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    8776           12 :                     .expect("lease request should succeed"),
    8777           12 :             );
    8778           12 :         });
    8779            4 : 
    8780            4 :         let updated_lease_0 = timeline
    8781            4 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    8782            4 :             .expect("lease renewal should succeed");
    8783            4 :         assert_eq!(
    8784            4 :             updated_lease_0.valid_until, leases[0].valid_until,
    8785            4 :             " Renewing with shorter lease should not change the lease."
    8786            4 :         );
    8787            4 : 
    8788            4 :         let updated_lease_1 = timeline
    8789            4 :             .renew_lsn_lease(
    8790            4 :                 Lsn(leased_lsns[1]),
    8791            4 :                 timeline.get_lsn_lease_length() * 2,
    8792            4 :                 &ctx,
    8793            4 :             )
    8794            4 :             .expect("lease renewal should succeed");
    8795            4 :         assert!(
    8796            4 :             updated_lease_1.valid_until > leases[1].valid_until,
    8797            4 :             "Renewing with a long lease should renew lease with later expiration time."
    8798            4 :         );
    8799            4 : 
    8800            4 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    8801            4 :         info!(
    8802            4 :             "applied_gc_cutoff_lsn: {}",
    8803            0 :             *timeline.get_applied_gc_cutoff_lsn()
    8804            4 :         );
    8805            4 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    8806            4 : 
    8807            4 :         let res = tenant
    8808            4 :             .gc_iteration(
    8809            4 :                 Some(TIMELINE_ID),
    8810            4 :                 0,
    8811            4 :                 Duration::ZERO,
    8812            4 :                 &CancellationToken::new(),
    8813            4 :                 &ctx,
    8814            4 :             )
    8815            4 :             .await
    8816            4 :             .unwrap();
    8817            4 : 
    8818            4 :         // Keeping everything <= Lsn(0x80) b/c leases:
    8819            4 :         // 0/10: initdb layer
    8820            4 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    8821            4 :         assert_eq!(res.layers_needed_by_leases, 7);
    8822            4 :         // Keeping 0/90 b/c it is the latest layer.
    8823            4 :         assert_eq!(res.layers_not_updated, 1);
    8824            4 :         // Removed 0/80.
    8825            4 :         assert_eq!(res.layers_removed, 1);
    8826            4 : 
    8827            4 :         // Make lease on a already GC-ed LSN.
    8828            4 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    8829            4 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    8830            4 :         timeline
    8831            4 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    8832            4 :             .expect_err("lease request on GC-ed LSN should fail");
    8833            4 : 
    8834            4 :         // Should still be able to renew a currently valid lease
    8835            4 :         // Assumption: original lease to is still valid for 0/50.
    8836            4 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    8837            4 :         timeline
    8838            4 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    8839            4 :             .expect("lease renewal with validation should succeed");
    8840            4 : 
    8841            4 :         Ok(())
    8842            4 :     }
    8843              : 
    8844              :     #[cfg(feature = "testing")]
    8845              :     #[tokio::test]
    8846            4 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    8847            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8848            4 :             "test_simple_bottom_most_compaction_deltas_1",
    8849            4 :             false,
    8850            4 :         )
    8851            4 :         .await
    8852            4 :     }
    8853              : 
    8854              :     #[cfg(feature = "testing")]
    8855              :     #[tokio::test]
    8856            4 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    8857            4 :         test_simple_bottom_most_compaction_deltas_helper(
    8858            4 :             "test_simple_bottom_most_compaction_deltas_2",
    8859            4 :             true,
    8860            4 :         )
    8861            4 :         .await
    8862            4 :     }
    8863              : 
    8864              :     #[cfg(feature = "testing")]
    8865            8 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    8866            8 :         test_name: &'static str,
    8867            8 :         use_delta_bottom_layer: bool,
    8868            8 :     ) -> anyhow::Result<()> {
    8869            8 :         let harness = TenantHarness::create(test_name).await?;
    8870            8 :         let (tenant, ctx) = harness.load().await;
    8871              : 
    8872          552 :         fn get_key(id: u32) -> Key {
    8873          552 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8874          552 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8875          552 :             key.field6 = id;
    8876          552 :             key
    8877          552 :         }
    8878              : 
    8879              :         // We create
    8880              :         // - one bottom-most image layer,
    8881              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8882              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8883              :         // - a delta layer D3 above the horizon.
    8884              :         //
    8885              :         //                             | D3 |
    8886              :         //  | D1 |
    8887              :         // -|    |-- gc horizon -----------------
    8888              :         //  |    |                | D2 |
    8889              :         // --------- img layer ------------------
    8890              :         //
    8891              :         // What we should expact from this compaction is:
    8892              :         //                             | D3 |
    8893              :         //  | Part of D1 |
    8894              :         // --------- img layer with D1+D2 at GC horizon------------------
    8895              : 
    8896              :         // img layer at 0x10
    8897            8 :         let img_layer = (0..10)
    8898           80 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8899            8 :             .collect_vec();
    8900            8 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    8901            8 :         let delta4 = (0..10)
    8902           80 :             .map(|id| {
    8903           80 :                 (
    8904           80 :                     get_key(id),
    8905           80 :                     Lsn(0x08),
    8906           80 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    8907           80 :                 )
    8908           80 :             })
    8909            8 :             .collect_vec();
    8910            8 : 
    8911            8 :         let delta1 = vec![
    8912            8 :             (
    8913            8 :                 get_key(1),
    8914            8 :                 Lsn(0x20),
    8915            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8916            8 :             ),
    8917            8 :             (
    8918            8 :                 get_key(2),
    8919            8 :                 Lsn(0x30),
    8920            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8921            8 :             ),
    8922            8 :             (
    8923            8 :                 get_key(3),
    8924            8 :                 Lsn(0x28),
    8925            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    8926            8 :             ),
    8927            8 :             (
    8928            8 :                 get_key(3),
    8929            8 :                 Lsn(0x30),
    8930            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    8931            8 :             ),
    8932            8 :             (
    8933            8 :                 get_key(3),
    8934            8 :                 Lsn(0x40),
    8935            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    8936            8 :             ),
    8937            8 :         ];
    8938            8 :         let delta2 = vec![
    8939            8 :             (
    8940            8 :                 get_key(5),
    8941            8 :                 Lsn(0x20),
    8942            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8943            8 :             ),
    8944            8 :             (
    8945            8 :                 get_key(6),
    8946            8 :                 Lsn(0x20),
    8947            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    8948            8 :             ),
    8949            8 :         ];
    8950            8 :         let delta3 = vec![
    8951            8 :             (
    8952            8 :                 get_key(8),
    8953            8 :                 Lsn(0x48),
    8954            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8955            8 :             ),
    8956            8 :             (
    8957            8 :                 get_key(9),
    8958            8 :                 Lsn(0x48),
    8959            8 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    8960            8 :             ),
    8961            8 :         ];
    8962              : 
    8963            8 :         let tline = if use_delta_bottom_layer {
    8964            4 :             tenant
    8965            4 :                 .create_test_timeline_with_layers(
    8966            4 :                     TIMELINE_ID,
    8967            4 :                     Lsn(0x08),
    8968            4 :                     DEFAULT_PG_VERSION,
    8969            4 :                     &ctx,
    8970            4 :                     vec![
    8971            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8972            4 :                             Lsn(0x08)..Lsn(0x10),
    8973            4 :                             delta4,
    8974            4 :                         ),
    8975            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8976            4 :                             Lsn(0x20)..Lsn(0x48),
    8977            4 :                             delta1,
    8978            4 :                         ),
    8979            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8980            4 :                             Lsn(0x20)..Lsn(0x48),
    8981            4 :                             delta2,
    8982            4 :                         ),
    8983            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    8984            4 :                             Lsn(0x48)..Lsn(0x50),
    8985            4 :                             delta3,
    8986            4 :                         ),
    8987            4 :                     ], // delta layers
    8988            4 :                     vec![], // image layers
    8989            4 :                     Lsn(0x50),
    8990            4 :                 )
    8991            4 :                 .await?
    8992              :         } else {
    8993            4 :             tenant
    8994            4 :                 .create_test_timeline_with_layers(
    8995            4 :                     TIMELINE_ID,
    8996            4 :                     Lsn(0x10),
    8997            4 :                     DEFAULT_PG_VERSION,
    8998            4 :                     &ctx,
    8999            4 :                     vec![
    9000            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9001            4 :                             Lsn(0x10)..Lsn(0x48),
    9002            4 :                             delta1,
    9003            4 :                         ),
    9004            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9005            4 :                             Lsn(0x10)..Lsn(0x48),
    9006            4 :                             delta2,
    9007            4 :                         ),
    9008            4 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9009            4 :                             Lsn(0x48)..Lsn(0x50),
    9010            4 :                             delta3,
    9011            4 :                         ),
    9012            4 :                     ], // delta layers
    9013            4 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9014            4 :                     Lsn(0x50),
    9015            4 :                 )
    9016            4 :                 .await?
    9017              :         };
    9018              :         {
    9019            8 :             tline
    9020            8 :                 .applied_gc_cutoff_lsn
    9021            8 :                 .lock_for_write()
    9022            8 :                 .store_and_unlock(Lsn(0x30))
    9023            8 :                 .wait()
    9024            8 :                 .await;
    9025              :             // Update GC info
    9026            8 :             let mut guard = tline.gc_info.write().unwrap();
    9027            8 :             *guard = GcInfo {
    9028            8 :                 retain_lsns: vec![],
    9029            8 :                 cutoffs: GcCutoffs {
    9030            8 :                     time: Lsn(0x30),
    9031            8 :                     space: Lsn(0x30),
    9032            8 :                 },
    9033            8 :                 leases: Default::default(),
    9034            8 :                 within_ancestor_pitr: false,
    9035            8 :             };
    9036            8 :         }
    9037            8 : 
    9038            8 :         let expected_result = [
    9039            8 :             Bytes::from_static(b"value 0@0x10"),
    9040            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9041            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9042            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9043            8 :             Bytes::from_static(b"value 4@0x10"),
    9044            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9045            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9046            8 :             Bytes::from_static(b"value 7@0x10"),
    9047            8 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9048            8 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9049            8 :         ];
    9050            8 : 
    9051            8 :         let expected_result_at_gc_horizon = [
    9052            8 :             Bytes::from_static(b"value 0@0x10"),
    9053            8 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9054            8 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9055            8 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9056            8 :             Bytes::from_static(b"value 4@0x10"),
    9057            8 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9058            8 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9059            8 :             Bytes::from_static(b"value 7@0x10"),
    9060            8 :             Bytes::from_static(b"value 8@0x10"),
    9061            8 :             Bytes::from_static(b"value 9@0x10"),
    9062            8 :         ];
    9063              : 
    9064           88 :         for idx in 0..10 {
    9065           80 :             assert_eq!(
    9066           80 :                 tline
    9067           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9068           80 :                     .await
    9069           80 :                     .unwrap(),
    9070           80 :                 &expected_result[idx]
    9071              :             );
    9072           80 :             assert_eq!(
    9073           80 :                 tline
    9074           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9075           80 :                     .await
    9076           80 :                     .unwrap(),
    9077           80 :                 &expected_result_at_gc_horizon[idx]
    9078              :             );
    9079              :         }
    9080              : 
    9081            8 :         let cancel = CancellationToken::new();
    9082            8 :         tline
    9083            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9084            8 :             .await
    9085            8 :             .unwrap();
    9086              : 
    9087           88 :         for idx in 0..10 {
    9088           80 :             assert_eq!(
    9089           80 :                 tline
    9090           80 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9091           80 :                     .await
    9092           80 :                     .unwrap(),
    9093           80 :                 &expected_result[idx]
    9094              :             );
    9095           80 :             assert_eq!(
    9096           80 :                 tline
    9097           80 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9098           80 :                     .await
    9099           80 :                     .unwrap(),
    9100           80 :                 &expected_result_at_gc_horizon[idx]
    9101              :             );
    9102              :         }
    9103              : 
    9104              :         // increase GC horizon and compact again
    9105              :         {
    9106            8 :             tline
    9107            8 :                 .applied_gc_cutoff_lsn
    9108            8 :                 .lock_for_write()
    9109            8 :                 .store_and_unlock(Lsn(0x40))
    9110            8 :                 .wait()
    9111            8 :                 .await;
    9112              :             // Update GC info
    9113            8 :             let mut guard = tline.gc_info.write().unwrap();
    9114            8 :             guard.cutoffs.time = Lsn(0x40);
    9115            8 :             guard.cutoffs.space = Lsn(0x40);
    9116            8 :         }
    9117            8 :         tline
    9118            8 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9119            8 :             .await
    9120            8 :             .unwrap();
    9121            8 : 
    9122            8 :         Ok(())
    9123            8 :     }
    9124              : 
    9125              :     #[cfg(feature = "testing")]
    9126              :     #[tokio::test]
    9127            4 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9128            4 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9129            4 :         let (tenant, ctx) = harness.load().await;
    9130            4 :         let tline = tenant
    9131            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9132            4 :             .await?;
    9133            4 :         tline.force_advance_lsn(Lsn(0x70));
    9134            4 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9135            4 :         let history = vec![
    9136            4 :             (
    9137            4 :                 key,
    9138            4 :                 Lsn(0x10),
    9139            4 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9140            4 :             ),
    9141            4 :             (
    9142            4 :                 key,
    9143            4 :                 Lsn(0x20),
    9144            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9145            4 :             ),
    9146            4 :             (
    9147            4 :                 key,
    9148            4 :                 Lsn(0x30),
    9149            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9150            4 :             ),
    9151            4 :             (
    9152            4 :                 key,
    9153            4 :                 Lsn(0x40),
    9154            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9155            4 :             ),
    9156            4 :             (
    9157            4 :                 key,
    9158            4 :                 Lsn(0x50),
    9159            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9160            4 :             ),
    9161            4 :             (
    9162            4 :                 key,
    9163            4 :                 Lsn(0x60),
    9164            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9165            4 :             ),
    9166            4 :             (
    9167            4 :                 key,
    9168            4 :                 Lsn(0x70),
    9169            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9170            4 :             ),
    9171            4 :             (
    9172            4 :                 key,
    9173            4 :                 Lsn(0x80),
    9174            4 :                 Value::Image(Bytes::copy_from_slice(
    9175            4 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9176            4 :                 )),
    9177            4 :             ),
    9178            4 :             (
    9179            4 :                 key,
    9180            4 :                 Lsn(0x90),
    9181            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9182            4 :             ),
    9183            4 :         ];
    9184            4 :         let res = tline
    9185            4 :             .generate_key_retention(
    9186            4 :                 key,
    9187            4 :                 &history,
    9188            4 :                 Lsn(0x60),
    9189            4 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9190            4 :                 3,
    9191            4 :                 None,
    9192            4 :             )
    9193            4 :             .await
    9194            4 :             .unwrap();
    9195            4 :         let expected_res = KeyHistoryRetention {
    9196            4 :             below_horizon: vec![
    9197            4 :                 (
    9198            4 :                     Lsn(0x20),
    9199            4 :                     KeyLogAtLsn(vec![(
    9200            4 :                         Lsn(0x20),
    9201            4 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9202            4 :                     )]),
    9203            4 :                 ),
    9204            4 :                 (
    9205            4 :                     Lsn(0x40),
    9206            4 :                     KeyLogAtLsn(vec![
    9207            4 :                         (
    9208            4 :                             Lsn(0x30),
    9209            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9210            4 :                         ),
    9211            4 :                         (
    9212            4 :                             Lsn(0x40),
    9213            4 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9214            4 :                         ),
    9215            4 :                     ]),
    9216            4 :                 ),
    9217            4 :                 (
    9218            4 :                     Lsn(0x50),
    9219            4 :                     KeyLogAtLsn(vec![(
    9220            4 :                         Lsn(0x50),
    9221            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9222            4 :                     )]),
    9223            4 :                 ),
    9224            4 :                 (
    9225            4 :                     Lsn(0x60),
    9226            4 :                     KeyLogAtLsn(vec![(
    9227            4 :                         Lsn(0x60),
    9228            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9229            4 :                     )]),
    9230            4 :                 ),
    9231            4 :             ],
    9232            4 :             above_horizon: KeyLogAtLsn(vec![
    9233            4 :                 (
    9234            4 :                     Lsn(0x70),
    9235            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9236            4 :                 ),
    9237            4 :                 (
    9238            4 :                     Lsn(0x80),
    9239            4 :                     Value::Image(Bytes::copy_from_slice(
    9240            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9241            4 :                     )),
    9242            4 :                 ),
    9243            4 :                 (
    9244            4 :                     Lsn(0x90),
    9245            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9246            4 :                 ),
    9247            4 :             ]),
    9248            4 :         };
    9249            4 :         assert_eq!(res, expected_res);
    9250            4 : 
    9251            4 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9252            4 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9253            4 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9254            4 :         // For example, we have
    9255            4 :         // ```plain
    9256            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9257            4 :         // ```
    9258            4 :         // Now the GC horizon moves up, and we have
    9259            4 :         // ```plain
    9260            4 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9261            4 :         // ```
    9262            4 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9263            4 :         // We will end up with
    9264            4 :         // ```plain
    9265            4 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9266            4 :         // ```
    9267            4 :         // Now we run the GC-compaction, and this key does not have a full history.
    9268            4 :         // We should be able to handle this partial history and drop everything before the
    9269            4 :         // gc_horizon image.
    9270            4 : 
    9271            4 :         let history = vec![
    9272            4 :             (
    9273            4 :                 key,
    9274            4 :                 Lsn(0x20),
    9275            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9276            4 :             ),
    9277            4 :             (
    9278            4 :                 key,
    9279            4 :                 Lsn(0x30),
    9280            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9281            4 :             ),
    9282            4 :             (
    9283            4 :                 key,
    9284            4 :                 Lsn(0x40),
    9285            4 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9286            4 :             ),
    9287            4 :             (
    9288            4 :                 key,
    9289            4 :                 Lsn(0x50),
    9290            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9291            4 :             ),
    9292            4 :             (
    9293            4 :                 key,
    9294            4 :                 Lsn(0x60),
    9295            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9296            4 :             ),
    9297            4 :             (
    9298            4 :                 key,
    9299            4 :                 Lsn(0x70),
    9300            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9301            4 :             ),
    9302            4 :             (
    9303            4 :                 key,
    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 :                 key,
    9311            4 :                 Lsn(0x90),
    9312            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9313            4 :             ),
    9314            4 :         ];
    9315            4 :         let res = tline
    9316            4 :             .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
    9317            4 :             .await
    9318            4 :             .unwrap();
    9319            4 :         let expected_res = KeyHistoryRetention {
    9320            4 :             below_horizon: vec![
    9321            4 :                 (
    9322            4 :                     Lsn(0x40),
    9323            4 :                     KeyLogAtLsn(vec![(
    9324            4 :                         Lsn(0x40),
    9325            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9326            4 :                     )]),
    9327            4 :                 ),
    9328            4 :                 (
    9329            4 :                     Lsn(0x50),
    9330            4 :                     KeyLogAtLsn(vec![(
    9331            4 :                         Lsn(0x50),
    9332            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9333            4 :                     )]),
    9334            4 :                 ),
    9335            4 :                 (
    9336            4 :                     Lsn(0x60),
    9337            4 :                     KeyLogAtLsn(vec![(
    9338            4 :                         Lsn(0x60),
    9339            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9340            4 :                     )]),
    9341            4 :                 ),
    9342            4 :             ],
    9343            4 :             above_horizon: KeyLogAtLsn(vec![
    9344            4 :                 (
    9345            4 :                     Lsn(0x70),
    9346            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9347            4 :                 ),
    9348            4 :                 (
    9349            4 :                     Lsn(0x80),
    9350            4 :                     Value::Image(Bytes::copy_from_slice(
    9351            4 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9352            4 :                     )),
    9353            4 :                 ),
    9354            4 :                 (
    9355            4 :                     Lsn(0x90),
    9356            4 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9357            4 :                 ),
    9358            4 :             ]),
    9359            4 :         };
    9360            4 :         assert_eq!(res, expected_res);
    9361            4 : 
    9362            4 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9363            4 :         // the ancestor image in the test case.
    9364            4 : 
    9365            4 :         let history = vec![
    9366            4 :             (
    9367            4 :                 key,
    9368            4 :                 Lsn(0x20),
    9369            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9370            4 :             ),
    9371            4 :             (
    9372            4 :                 key,
    9373            4 :                 Lsn(0x30),
    9374            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9375            4 :             ),
    9376            4 :             (
    9377            4 :                 key,
    9378            4 :                 Lsn(0x40),
    9379            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9380            4 :             ),
    9381            4 :             (
    9382            4 :                 key,
    9383            4 :                 Lsn(0x70),
    9384            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9385            4 :             ),
    9386            4 :         ];
    9387            4 :         let res = tline
    9388            4 :             .generate_key_retention(
    9389            4 :                 key,
    9390            4 :                 &history,
    9391            4 :                 Lsn(0x60),
    9392            4 :                 &[],
    9393            4 :                 3,
    9394            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9395            4 :             )
    9396            4 :             .await
    9397            4 :             .unwrap();
    9398            4 :         let expected_res = KeyHistoryRetention {
    9399            4 :             below_horizon: vec![(
    9400            4 :                 Lsn(0x60),
    9401            4 :                 KeyLogAtLsn(vec![(
    9402            4 :                     Lsn(0x60),
    9403            4 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9404            4 :                 )]),
    9405            4 :             )],
    9406            4 :             above_horizon: KeyLogAtLsn(vec![(
    9407            4 :                 Lsn(0x70),
    9408            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9409            4 :             )]),
    9410            4 :         };
    9411            4 :         assert_eq!(res, expected_res);
    9412            4 : 
    9413            4 :         let history = vec![
    9414            4 :             (
    9415            4 :                 key,
    9416            4 :                 Lsn(0x20),
    9417            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9418            4 :             ),
    9419            4 :             (
    9420            4 :                 key,
    9421            4 :                 Lsn(0x40),
    9422            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9423            4 :             ),
    9424            4 :             (
    9425            4 :                 key,
    9426            4 :                 Lsn(0x60),
    9427            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9428            4 :             ),
    9429            4 :             (
    9430            4 :                 key,
    9431            4 :                 Lsn(0x70),
    9432            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9433            4 :             ),
    9434            4 :         ];
    9435            4 :         let res = tline
    9436            4 :             .generate_key_retention(
    9437            4 :                 key,
    9438            4 :                 &history,
    9439            4 :                 Lsn(0x60),
    9440            4 :                 &[Lsn(0x30)],
    9441            4 :                 3,
    9442            4 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9443            4 :             )
    9444            4 :             .await
    9445            4 :             .unwrap();
    9446            4 :         let expected_res = KeyHistoryRetention {
    9447            4 :             below_horizon: vec![
    9448            4 :                 (
    9449            4 :                     Lsn(0x30),
    9450            4 :                     KeyLogAtLsn(vec![(
    9451            4 :                         Lsn(0x20),
    9452            4 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9453            4 :                     )]),
    9454            4 :                 ),
    9455            4 :                 (
    9456            4 :                     Lsn(0x60),
    9457            4 :                     KeyLogAtLsn(vec![(
    9458            4 :                         Lsn(0x60),
    9459            4 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9460            4 :                     )]),
    9461            4 :                 ),
    9462            4 :             ],
    9463            4 :             above_horizon: KeyLogAtLsn(vec![(
    9464            4 :                 Lsn(0x70),
    9465            4 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9466            4 :             )]),
    9467            4 :         };
    9468            4 :         assert_eq!(res, expected_res);
    9469            4 : 
    9470            4 :         Ok(())
    9471            4 :     }
    9472              : 
    9473              :     #[cfg(feature = "testing")]
    9474              :     #[tokio::test]
    9475            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9476            4 :         let harness =
    9477            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9478            4 :         let (tenant, ctx) = harness.load().await;
    9479            4 : 
    9480         1036 :         fn get_key(id: u32) -> Key {
    9481         1036 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9482         1036 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9483         1036 :             key.field6 = id;
    9484         1036 :             key
    9485         1036 :         }
    9486            4 : 
    9487            4 :         let img_layer = (0..10)
    9488           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9489            4 :             .collect_vec();
    9490            4 : 
    9491            4 :         let delta1 = vec![
    9492            4 :             (
    9493            4 :                 get_key(1),
    9494            4 :                 Lsn(0x20),
    9495            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9496            4 :             ),
    9497            4 :             (
    9498            4 :                 get_key(2),
    9499            4 :                 Lsn(0x30),
    9500            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9501            4 :             ),
    9502            4 :             (
    9503            4 :                 get_key(3),
    9504            4 :                 Lsn(0x28),
    9505            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9506            4 :             ),
    9507            4 :             (
    9508            4 :                 get_key(3),
    9509            4 :                 Lsn(0x30),
    9510            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9511            4 :             ),
    9512            4 :             (
    9513            4 :                 get_key(3),
    9514            4 :                 Lsn(0x40),
    9515            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9516            4 :             ),
    9517            4 :         ];
    9518            4 :         let delta2 = vec![
    9519            4 :             (
    9520            4 :                 get_key(5),
    9521            4 :                 Lsn(0x20),
    9522            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9523            4 :             ),
    9524            4 :             (
    9525            4 :                 get_key(6),
    9526            4 :                 Lsn(0x20),
    9527            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9528            4 :             ),
    9529            4 :         ];
    9530            4 :         let delta3 = vec![
    9531            4 :             (
    9532            4 :                 get_key(8),
    9533            4 :                 Lsn(0x48),
    9534            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9535            4 :             ),
    9536            4 :             (
    9537            4 :                 get_key(9),
    9538            4 :                 Lsn(0x48),
    9539            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9540            4 :             ),
    9541            4 :         ];
    9542            4 : 
    9543            4 :         let tline = tenant
    9544            4 :             .create_test_timeline_with_layers(
    9545            4 :                 TIMELINE_ID,
    9546            4 :                 Lsn(0x10),
    9547            4 :                 DEFAULT_PG_VERSION,
    9548            4 :                 &ctx,
    9549            4 :                 vec![
    9550            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
    9551            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
    9552            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9553            4 :                 ], // delta layers
    9554            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9555            4 :                 Lsn(0x50),
    9556            4 :             )
    9557            4 :             .await?;
    9558            4 :         {
    9559            4 :             tline
    9560            4 :                 .applied_gc_cutoff_lsn
    9561            4 :                 .lock_for_write()
    9562            4 :                 .store_and_unlock(Lsn(0x30))
    9563            4 :                 .wait()
    9564            4 :                 .await;
    9565            4 :             // Update GC info
    9566            4 :             let mut guard = tline.gc_info.write().unwrap();
    9567            4 :             *guard = GcInfo {
    9568            4 :                 retain_lsns: vec![
    9569            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9570            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9571            4 :                 ],
    9572            4 :                 cutoffs: GcCutoffs {
    9573            4 :                     time: Lsn(0x30),
    9574            4 :                     space: Lsn(0x30),
    9575            4 :                 },
    9576            4 :                 leases: Default::default(),
    9577            4 :                 within_ancestor_pitr: false,
    9578            4 :             };
    9579            4 :         }
    9580            4 : 
    9581            4 :         let expected_result = [
    9582            4 :             Bytes::from_static(b"value 0@0x10"),
    9583            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9584            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9585            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9586            4 :             Bytes::from_static(b"value 4@0x10"),
    9587            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9588            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9589            4 :             Bytes::from_static(b"value 7@0x10"),
    9590            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9591            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9592            4 :         ];
    9593            4 : 
    9594            4 :         let expected_result_at_gc_horizon = [
    9595            4 :             Bytes::from_static(b"value 0@0x10"),
    9596            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9597            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9598            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9599            4 :             Bytes::from_static(b"value 4@0x10"),
    9600            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9601            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9602            4 :             Bytes::from_static(b"value 7@0x10"),
    9603            4 :             Bytes::from_static(b"value 8@0x10"),
    9604            4 :             Bytes::from_static(b"value 9@0x10"),
    9605            4 :         ];
    9606            4 : 
    9607            4 :         let expected_result_at_lsn_20 = [
    9608            4 :             Bytes::from_static(b"value 0@0x10"),
    9609            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9610            4 :             Bytes::from_static(b"value 2@0x10"),
    9611            4 :             Bytes::from_static(b"value 3@0x10"),
    9612            4 :             Bytes::from_static(b"value 4@0x10"),
    9613            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9614            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9615            4 :             Bytes::from_static(b"value 7@0x10"),
    9616            4 :             Bytes::from_static(b"value 8@0x10"),
    9617            4 :             Bytes::from_static(b"value 9@0x10"),
    9618            4 :         ];
    9619            4 : 
    9620            4 :         let expected_result_at_lsn_10 = [
    9621            4 :             Bytes::from_static(b"value 0@0x10"),
    9622            4 :             Bytes::from_static(b"value 1@0x10"),
    9623            4 :             Bytes::from_static(b"value 2@0x10"),
    9624            4 :             Bytes::from_static(b"value 3@0x10"),
    9625            4 :             Bytes::from_static(b"value 4@0x10"),
    9626            4 :             Bytes::from_static(b"value 5@0x10"),
    9627            4 :             Bytes::from_static(b"value 6@0x10"),
    9628            4 :             Bytes::from_static(b"value 7@0x10"),
    9629            4 :             Bytes::from_static(b"value 8@0x10"),
    9630            4 :             Bytes::from_static(b"value 9@0x10"),
    9631            4 :         ];
    9632            4 : 
    9633           24 :         let verify_result = || async {
    9634           24 :             let gc_horizon = {
    9635           24 :                 let gc_info = tline.gc_info.read().unwrap();
    9636           24 :                 gc_info.cutoffs.time
    9637            4 :             };
    9638          264 :             for idx in 0..10 {
    9639          240 :                 assert_eq!(
    9640          240 :                     tline
    9641          240 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9642          240 :                         .await
    9643          240 :                         .unwrap(),
    9644          240 :                     &expected_result[idx]
    9645            4 :                 );
    9646          240 :                 assert_eq!(
    9647          240 :                     tline
    9648          240 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9649          240 :                         .await
    9650          240 :                         .unwrap(),
    9651          240 :                     &expected_result_at_gc_horizon[idx]
    9652            4 :                 );
    9653          240 :                 assert_eq!(
    9654          240 :                     tline
    9655          240 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9656          240 :                         .await
    9657          240 :                         .unwrap(),
    9658          240 :                     &expected_result_at_lsn_20[idx]
    9659            4 :                 );
    9660          240 :                 assert_eq!(
    9661          240 :                     tline
    9662          240 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9663          240 :                         .await
    9664          240 :                         .unwrap(),
    9665          240 :                     &expected_result_at_lsn_10[idx]
    9666            4 :                 );
    9667            4 :             }
    9668           48 :         };
    9669            4 : 
    9670            4 :         verify_result().await;
    9671            4 : 
    9672            4 :         let cancel = CancellationToken::new();
    9673            4 :         let mut dryrun_flags = EnumSet::new();
    9674            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9675            4 : 
    9676            4 :         tline
    9677            4 :             .compact_with_gc(
    9678            4 :                 &cancel,
    9679            4 :                 CompactOptions {
    9680            4 :                     flags: dryrun_flags,
    9681            4 :                     ..Default::default()
    9682            4 :                 },
    9683            4 :                 &ctx,
    9684            4 :             )
    9685            4 :             .await
    9686            4 :             .unwrap();
    9687            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
    9688            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9689            4 :         verify_result().await;
    9690            4 : 
    9691            4 :         tline
    9692            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9693            4 :             .await
    9694            4 :             .unwrap();
    9695            4 :         verify_result().await;
    9696            4 : 
    9697            4 :         // compact again
    9698            4 :         tline
    9699            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9700            4 :             .await
    9701            4 :             .unwrap();
    9702            4 :         verify_result().await;
    9703            4 : 
    9704            4 :         // increase GC horizon and compact again
    9705            4 :         {
    9706            4 :             tline
    9707            4 :                 .applied_gc_cutoff_lsn
    9708            4 :                 .lock_for_write()
    9709            4 :                 .store_and_unlock(Lsn(0x38))
    9710            4 :                 .wait()
    9711            4 :                 .await;
    9712            4 :             // Update GC info
    9713            4 :             let mut guard = tline.gc_info.write().unwrap();
    9714            4 :             guard.cutoffs.time = Lsn(0x38);
    9715            4 :             guard.cutoffs.space = Lsn(0x38);
    9716            4 :         }
    9717            4 :         tline
    9718            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9719            4 :             .await
    9720            4 :             .unwrap();
    9721            4 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
    9722            4 : 
    9723            4 :         // not increasing the GC horizon and compact again
    9724            4 :         tline
    9725            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9726            4 :             .await
    9727            4 :             .unwrap();
    9728            4 :         verify_result().await;
    9729            4 : 
    9730            4 :         Ok(())
    9731            4 :     }
    9732              : 
    9733              :     #[cfg(feature = "testing")]
    9734              :     #[tokio::test]
    9735            4 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
    9736            4 :     {
    9737            4 :         let harness =
    9738            4 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
    9739            4 :                 .await?;
    9740            4 :         let (tenant, ctx) = harness.load().await;
    9741            4 : 
    9742          704 :         fn get_key(id: u32) -> Key {
    9743          704 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9744          704 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9745          704 :             key.field6 = id;
    9746          704 :             key
    9747          704 :         }
    9748            4 : 
    9749            4 :         let img_layer = (0..10)
    9750           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9751            4 :             .collect_vec();
    9752            4 : 
    9753            4 :         let delta1 = vec![
    9754            4 :             (
    9755            4 :                 get_key(1),
    9756            4 :                 Lsn(0x20),
    9757            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9758            4 :             ),
    9759            4 :             (
    9760            4 :                 get_key(1),
    9761            4 :                 Lsn(0x28),
    9762            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9763            4 :             ),
    9764            4 :         ];
    9765            4 :         let delta2 = vec![
    9766            4 :             (
    9767            4 :                 get_key(1),
    9768            4 :                 Lsn(0x30),
    9769            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9770            4 :             ),
    9771            4 :             (
    9772            4 :                 get_key(1),
    9773            4 :                 Lsn(0x38),
    9774            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
    9775            4 :             ),
    9776            4 :         ];
    9777            4 :         let delta3 = vec![
    9778            4 :             (
    9779            4 :                 get_key(8),
    9780            4 :                 Lsn(0x48),
    9781            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9782            4 :             ),
    9783            4 :             (
    9784            4 :                 get_key(9),
    9785            4 :                 Lsn(0x48),
    9786            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9787            4 :             ),
    9788            4 :         ];
    9789            4 : 
    9790            4 :         let tline = tenant
    9791            4 :             .create_test_timeline_with_layers(
    9792            4 :                 TIMELINE_ID,
    9793            4 :                 Lsn(0x10),
    9794            4 :                 DEFAULT_PG_VERSION,
    9795            4 :                 &ctx,
    9796            4 :                 vec![
    9797            4 :                     // delta1 and delta 2 only contain a single key but multiple updates
    9798            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
    9799            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
    9800            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
    9801            4 :                 ], // delta layers
    9802            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9803            4 :                 Lsn(0x50),
    9804            4 :             )
    9805            4 :             .await?;
    9806            4 :         {
    9807            4 :             tline
    9808            4 :                 .applied_gc_cutoff_lsn
    9809            4 :                 .lock_for_write()
    9810            4 :                 .store_and_unlock(Lsn(0x30))
    9811            4 :                 .wait()
    9812            4 :                 .await;
    9813            4 :             // Update GC info
    9814            4 :             let mut guard = tline.gc_info.write().unwrap();
    9815            4 :             *guard = GcInfo {
    9816            4 :                 retain_lsns: vec![
    9817            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
    9818            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
    9819            4 :                 ],
    9820            4 :                 cutoffs: GcCutoffs {
    9821            4 :                     time: Lsn(0x30),
    9822            4 :                     space: Lsn(0x30),
    9823            4 :                 },
    9824            4 :                 leases: Default::default(),
    9825            4 :                 within_ancestor_pitr: false,
    9826            4 :             };
    9827            4 :         }
    9828            4 : 
    9829            4 :         let expected_result = [
    9830            4 :             Bytes::from_static(b"value 0@0x10"),
    9831            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
    9832            4 :             Bytes::from_static(b"value 2@0x10"),
    9833            4 :             Bytes::from_static(b"value 3@0x10"),
    9834            4 :             Bytes::from_static(b"value 4@0x10"),
    9835            4 :             Bytes::from_static(b"value 5@0x10"),
    9836            4 :             Bytes::from_static(b"value 6@0x10"),
    9837            4 :             Bytes::from_static(b"value 7@0x10"),
    9838            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9839            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9840            4 :         ];
    9841            4 : 
    9842            4 :         let expected_result_at_gc_horizon = [
    9843            4 :             Bytes::from_static(b"value 0@0x10"),
    9844            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
    9845            4 :             Bytes::from_static(b"value 2@0x10"),
    9846            4 :             Bytes::from_static(b"value 3@0x10"),
    9847            4 :             Bytes::from_static(b"value 4@0x10"),
    9848            4 :             Bytes::from_static(b"value 5@0x10"),
    9849            4 :             Bytes::from_static(b"value 6@0x10"),
    9850            4 :             Bytes::from_static(b"value 7@0x10"),
    9851            4 :             Bytes::from_static(b"value 8@0x10"),
    9852            4 :             Bytes::from_static(b"value 9@0x10"),
    9853            4 :         ];
    9854            4 : 
    9855            4 :         let expected_result_at_lsn_20 = [
    9856            4 :             Bytes::from_static(b"value 0@0x10"),
    9857            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9858            4 :             Bytes::from_static(b"value 2@0x10"),
    9859            4 :             Bytes::from_static(b"value 3@0x10"),
    9860            4 :             Bytes::from_static(b"value 4@0x10"),
    9861            4 :             Bytes::from_static(b"value 5@0x10"),
    9862            4 :             Bytes::from_static(b"value 6@0x10"),
    9863            4 :             Bytes::from_static(b"value 7@0x10"),
    9864            4 :             Bytes::from_static(b"value 8@0x10"),
    9865            4 :             Bytes::from_static(b"value 9@0x10"),
    9866            4 :         ];
    9867            4 : 
    9868            4 :         let expected_result_at_lsn_10 = [
    9869            4 :             Bytes::from_static(b"value 0@0x10"),
    9870            4 :             Bytes::from_static(b"value 1@0x10"),
    9871            4 :             Bytes::from_static(b"value 2@0x10"),
    9872            4 :             Bytes::from_static(b"value 3@0x10"),
    9873            4 :             Bytes::from_static(b"value 4@0x10"),
    9874            4 :             Bytes::from_static(b"value 5@0x10"),
    9875            4 :             Bytes::from_static(b"value 6@0x10"),
    9876            4 :             Bytes::from_static(b"value 7@0x10"),
    9877            4 :             Bytes::from_static(b"value 8@0x10"),
    9878            4 :             Bytes::from_static(b"value 9@0x10"),
    9879            4 :         ];
    9880            4 : 
    9881           16 :         let verify_result = || async {
    9882           16 :             let gc_horizon = {
    9883           16 :                 let gc_info = tline.gc_info.read().unwrap();
    9884           16 :                 gc_info.cutoffs.time
    9885            4 :             };
    9886          176 :             for idx in 0..10 {
    9887          160 :                 assert_eq!(
    9888          160 :                     tline
    9889          160 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9890          160 :                         .await
    9891          160 :                         .unwrap(),
    9892          160 :                     &expected_result[idx]
    9893            4 :                 );
    9894          160 :                 assert_eq!(
    9895          160 :                     tline
    9896          160 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
    9897          160 :                         .await
    9898          160 :                         .unwrap(),
    9899          160 :                     &expected_result_at_gc_horizon[idx]
    9900            4 :                 );
    9901          160 :                 assert_eq!(
    9902          160 :                     tline
    9903          160 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
    9904          160 :                         .await
    9905          160 :                         .unwrap(),
    9906          160 :                     &expected_result_at_lsn_20[idx]
    9907            4 :                 );
    9908          160 :                 assert_eq!(
    9909          160 :                     tline
    9910          160 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
    9911          160 :                         .await
    9912          160 :                         .unwrap(),
    9913          160 :                     &expected_result_at_lsn_10[idx]
    9914            4 :                 );
    9915            4 :             }
    9916           32 :         };
    9917            4 : 
    9918            4 :         verify_result().await;
    9919            4 : 
    9920            4 :         let cancel = CancellationToken::new();
    9921            4 :         let mut dryrun_flags = EnumSet::new();
    9922            4 :         dryrun_flags.insert(CompactFlags::DryRun);
    9923            4 : 
    9924            4 :         tline
    9925            4 :             .compact_with_gc(
    9926            4 :                 &cancel,
    9927            4 :                 CompactOptions {
    9928            4 :                     flags: dryrun_flags,
    9929            4 :                     ..Default::default()
    9930            4 :                 },
    9931            4 :                 &ctx,
    9932            4 :             )
    9933            4 :             .await
    9934            4 :             .unwrap();
    9935            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
    9936            4 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
    9937            4 :         verify_result().await;
    9938            4 : 
    9939            4 :         tline
    9940            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9941            4 :             .await
    9942            4 :             .unwrap();
    9943            4 :         verify_result().await;
    9944            4 : 
    9945            4 :         // compact again
    9946            4 :         tline
    9947            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9948            4 :             .await
    9949            4 :             .unwrap();
    9950            4 :         verify_result().await;
    9951            4 : 
    9952            4 :         Ok(())
    9953            4 :     }
    9954              : 
    9955              :     #[cfg(feature = "testing")]
    9956              :     #[tokio::test]
    9957            4 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
    9958            4 :         use models::CompactLsnRange;
    9959            4 : 
    9960            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
    9961            4 :         let (tenant, ctx) = harness.load().await;
    9962            4 : 
    9963          332 :         fn get_key(id: u32) -> Key {
    9964          332 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    9965          332 :             key.field6 = id;
    9966          332 :             key
    9967          332 :         }
    9968            4 : 
    9969            4 :         let img_layer = (0..10)
    9970           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9971            4 :             .collect_vec();
    9972            4 : 
    9973            4 :         let delta1 = vec![
    9974            4 :             (
    9975            4 :                 get_key(1),
    9976            4 :                 Lsn(0x20),
    9977            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9978            4 :             ),
    9979            4 :             (
    9980            4 :                 get_key(2),
    9981            4 :                 Lsn(0x30),
    9982            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9983            4 :             ),
    9984            4 :             (
    9985            4 :                 get_key(3),
    9986            4 :                 Lsn(0x28),
    9987            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9988            4 :             ),
    9989            4 :             (
    9990            4 :                 get_key(3),
    9991            4 :                 Lsn(0x30),
    9992            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9993            4 :             ),
    9994            4 :             (
    9995            4 :                 get_key(3),
    9996            4 :                 Lsn(0x40),
    9997            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9998            4 :             ),
    9999            4 :         ];
   10000            4 :         let delta2 = vec![
   10001            4 :             (
   10002            4 :                 get_key(5),
   10003            4 :                 Lsn(0x20),
   10004            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10005            4 :             ),
   10006            4 :             (
   10007            4 :                 get_key(6),
   10008            4 :                 Lsn(0x20),
   10009            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10010            4 :             ),
   10011            4 :         ];
   10012            4 :         let delta3 = vec![
   10013            4 :             (
   10014            4 :                 get_key(8),
   10015            4 :                 Lsn(0x48),
   10016            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10017            4 :             ),
   10018            4 :             (
   10019            4 :                 get_key(9),
   10020            4 :                 Lsn(0x48),
   10021            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10022            4 :             ),
   10023            4 :         ];
   10024            4 : 
   10025            4 :         let parent_tline = tenant
   10026            4 :             .create_test_timeline_with_layers(
   10027            4 :                 TIMELINE_ID,
   10028            4 :                 Lsn(0x10),
   10029            4 :                 DEFAULT_PG_VERSION,
   10030            4 :                 &ctx,
   10031            4 :                 vec![],                       // delta layers
   10032            4 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10033            4 :                 Lsn(0x18),
   10034            4 :             )
   10035            4 :             .await?;
   10036            4 : 
   10037            4 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10038            4 : 
   10039            4 :         let branch_tline = tenant
   10040            4 :             .branch_timeline_test_with_layers(
   10041            4 :                 &parent_tline,
   10042            4 :                 NEW_TIMELINE_ID,
   10043            4 :                 Some(Lsn(0x18)),
   10044            4 :                 &ctx,
   10045            4 :                 vec![
   10046            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10047            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10048            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10049            4 :                 ], // delta layers
   10050            4 :                 vec![], // image layers
   10051            4 :                 Lsn(0x50),
   10052            4 :             )
   10053            4 :             .await?;
   10054            4 : 
   10055            4 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10056            4 : 
   10057            4 :         {
   10058            4 :             parent_tline
   10059            4 :                 .applied_gc_cutoff_lsn
   10060            4 :                 .lock_for_write()
   10061            4 :                 .store_and_unlock(Lsn(0x10))
   10062            4 :                 .wait()
   10063            4 :                 .await;
   10064            4 :             // Update GC info
   10065            4 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10066            4 :             *guard = GcInfo {
   10067            4 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10068            4 :                 cutoffs: GcCutoffs {
   10069            4 :                     time: Lsn(0x10),
   10070            4 :                     space: Lsn(0x10),
   10071            4 :                 },
   10072            4 :                 leases: Default::default(),
   10073            4 :                 within_ancestor_pitr: false,
   10074            4 :             };
   10075            4 :         }
   10076            4 : 
   10077            4 :         {
   10078            4 :             branch_tline
   10079            4 :                 .applied_gc_cutoff_lsn
   10080            4 :                 .lock_for_write()
   10081            4 :                 .store_and_unlock(Lsn(0x50))
   10082            4 :                 .wait()
   10083            4 :                 .await;
   10084            4 :             // Update GC info
   10085            4 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10086            4 :             *guard = GcInfo {
   10087            4 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10088            4 :                 cutoffs: GcCutoffs {
   10089            4 :                     time: Lsn(0x50),
   10090            4 :                     space: Lsn(0x50),
   10091            4 :                 },
   10092            4 :                 leases: Default::default(),
   10093            4 :                 within_ancestor_pitr: false,
   10094            4 :             };
   10095            4 :         }
   10096            4 : 
   10097            4 :         let expected_result_at_gc_horizon = [
   10098            4 :             Bytes::from_static(b"value 0@0x10"),
   10099            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10100            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10101            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10102            4 :             Bytes::from_static(b"value 4@0x10"),
   10103            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10104            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10105            4 :             Bytes::from_static(b"value 7@0x10"),
   10106            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10107            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10108            4 :         ];
   10109            4 : 
   10110            4 :         let expected_result_at_lsn_40 = [
   10111            4 :             Bytes::from_static(b"value 0@0x10"),
   10112            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10113            4 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10114            4 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10115            4 :             Bytes::from_static(b"value 4@0x10"),
   10116            4 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10117            4 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10118            4 :             Bytes::from_static(b"value 7@0x10"),
   10119            4 :             Bytes::from_static(b"value 8@0x10"),
   10120            4 :             Bytes::from_static(b"value 9@0x10"),
   10121            4 :         ];
   10122            4 : 
   10123           12 :         let verify_result = || async {
   10124          132 :             for idx in 0..10 {
   10125          120 :                 assert_eq!(
   10126          120 :                     branch_tline
   10127          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10128          120 :                         .await
   10129          120 :                         .unwrap(),
   10130          120 :                     &expected_result_at_gc_horizon[idx]
   10131            4 :                 );
   10132          120 :                 assert_eq!(
   10133          120 :                     branch_tline
   10134          120 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10135          120 :                         .await
   10136          120 :                         .unwrap(),
   10137          120 :                     &expected_result_at_lsn_40[idx]
   10138            4 :                 );
   10139            4 :             }
   10140           24 :         };
   10141            4 : 
   10142            4 :         verify_result().await;
   10143            4 : 
   10144            4 :         let cancel = CancellationToken::new();
   10145            4 :         branch_tline
   10146            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10147            4 :             .await
   10148            4 :             .unwrap();
   10149            4 : 
   10150            4 :         verify_result().await;
   10151            4 : 
   10152            4 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10153            4 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10154            4 :         branch_tline
   10155            4 :             .compact_with_gc(
   10156            4 :                 &cancel,
   10157            4 :                 CompactOptions {
   10158            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10159            4 :                     ..Default::default()
   10160            4 :                 },
   10161            4 :                 &ctx,
   10162            4 :             )
   10163            4 :             .await
   10164            4 :             .unwrap();
   10165            4 : 
   10166            4 :         verify_result().await;
   10167            4 : 
   10168            4 :         Ok(())
   10169            4 :     }
   10170              : 
   10171              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10172              :     // Create an image arrangement where we have to read at different LSN ranges
   10173              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10174              :     // a delta layer. Like so:
   10175              :     //
   10176              :     //     A      B
   10177              :     // +----------------+ -> delta_layer
   10178              :     // |                |                           ^ lsn
   10179              :     // |       =========|-> nested_image_layer      |
   10180              :     // |       C        |                           |
   10181              :     // +----------------+                           |
   10182              :     // ======== -> baseline_image_layer             +-------> key
   10183              :     //
   10184              :     //
   10185              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10186              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10187              :     #[cfg(feature = "testing")]
   10188              :     #[tokio::test]
   10189            4 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10190            4 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10191            4 :         let (tenant, ctx) = harness.load().await;
   10192            4 : 
   10193            4 :         let will_init_keys = [2, 6];
   10194           88 :         fn get_key(id: u32) -> Key {
   10195           88 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10196           88 :             key.field6 = id;
   10197           88 :             key
   10198           88 :         }
   10199            4 : 
   10200            4 :         let mut expected_key_values = HashMap::new();
   10201            4 : 
   10202            4 :         let baseline_image_layer_lsn = Lsn(0x10);
   10203            4 :         let mut baseline_img_layer = Vec::new();
   10204           24 :         for i in 0..5 {
   10205           20 :             let key = get_key(i);
   10206           20 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10207           20 : 
   10208           20 :             let removed = expected_key_values.insert(key, value.clone());
   10209           20 :             assert!(removed.is_none());
   10210            4 : 
   10211           20 :             baseline_img_layer.push((key, Bytes::from(value)));
   10212            4 :         }
   10213            4 : 
   10214            4 :         let nested_image_layer_lsn = Lsn(0x50);
   10215            4 :         let mut nested_img_layer = Vec::new();
   10216           24 :         for i in 5..10 {
   10217           20 :             let key = get_key(i);
   10218           20 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10219           20 : 
   10220           20 :             let removed = expected_key_values.insert(key, value.clone());
   10221           20 :             assert!(removed.is_none());
   10222            4 : 
   10223           20 :             nested_img_layer.push((key, Bytes::from(value)));
   10224            4 :         }
   10225            4 : 
   10226            4 :         let mut delta_layer_spec = Vec::default();
   10227            4 :         let delta_layer_start_lsn = Lsn(0x20);
   10228            4 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10229            4 : 
   10230           44 :         for i in 0..10 {
   10231           40 :             let key = get_key(i);
   10232           40 :             let key_in_nested = nested_img_layer
   10233           40 :                 .iter()
   10234          160 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10235           40 :             let lsn = {
   10236           40 :                 if key_in_nested {
   10237           20 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10238            4 :                 } else {
   10239           20 :                     delta_layer_start_lsn
   10240            4 :                 }
   10241            4 :             };
   10242            4 : 
   10243           40 :             let will_init = will_init_keys.contains(&i);
   10244           40 :             if will_init {
   10245            8 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10246            8 : 
   10247            8 :                 expected_key_values.insert(key, "".to_string());
   10248           32 :             } else {
   10249           32 :                 let delta = format!("@{lsn}");
   10250           32 :                 delta_layer_spec.push((
   10251           32 :                     key,
   10252           32 :                     lsn,
   10253           32 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10254           32 :                 ));
   10255           32 : 
   10256           32 :                 expected_key_values
   10257           32 :                     .get_mut(&key)
   10258           32 :                     .expect("An image exists for each key")
   10259           32 :                     .push_str(delta.as_str());
   10260           32 :             }
   10261           40 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10262            4 :         }
   10263            4 : 
   10264            4 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10265            4 : 
   10266            4 :         assert!(
   10267            4 :             nested_image_layer_lsn > delta_layer_start_lsn
   10268            4 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10269            4 :         );
   10270            4 : 
   10271            4 :         let tline = tenant
   10272            4 :             .create_test_timeline_with_layers(
   10273            4 :                 TIMELINE_ID,
   10274            4 :                 baseline_image_layer_lsn,
   10275            4 :                 DEFAULT_PG_VERSION,
   10276            4 :                 &ctx,
   10277            4 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10278            4 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10279            4 :                     delta_layer_spec,
   10280            4 :                 )], // delta layers
   10281            4 :                 vec![
   10282            4 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10283            4 :                     (nested_image_layer_lsn, nested_img_layer),
   10284            4 :                 ], // image layers
   10285            4 :                 delta_layer_end_lsn,
   10286            4 :             )
   10287            4 :             .await?;
   10288            4 : 
   10289            4 :         let keyspace = KeySpace::single(get_key(0)..get_key(10));
   10290            4 :         let results = tline
   10291            4 :             .get_vectored(
   10292            4 :                 keyspace,
   10293            4 :                 delta_layer_end_lsn,
   10294            4 :                 IoConcurrency::sequential(),
   10295            4 :                 &ctx,
   10296            4 :             )
   10297            4 :             .await
   10298            4 :             .expect("No vectored errors");
   10299           44 :         for (key, res) in results {
   10300           40 :             let value = res.expect("No key errors");
   10301           40 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10302           40 :             assert_eq!(value, Bytes::from(expected_value));
   10303            4 :         }
   10304            4 : 
   10305            4 :         Ok(())
   10306            4 :     }
   10307              : 
   10308          428 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   10309          428 :         (
   10310          428 :             k1.is_delta,
   10311          428 :             k1.key_range.start,
   10312          428 :             k1.key_range.end,
   10313          428 :             k1.lsn_range.start,
   10314          428 :             k1.lsn_range.end,
   10315          428 :         )
   10316          428 :             .cmp(&(
   10317          428 :                 k2.is_delta,
   10318          428 :                 k2.key_range.start,
   10319          428 :                 k2.key_range.end,
   10320          428 :                 k2.lsn_range.start,
   10321          428 :                 k2.lsn_range.end,
   10322          428 :             ))
   10323          428 :     }
   10324              : 
   10325           48 :     async fn inspect_and_sort(
   10326           48 :         tline: &Arc<Timeline>,
   10327           48 :         filter: Option<std::ops::Range<Key>>,
   10328           48 :     ) -> Vec<PersistentLayerKey> {
   10329           48 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   10330           48 :         if let Some(filter) = filter {
   10331          216 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   10332           44 :         }
   10333           48 :         all_layers.sort_by(sort_layer_key);
   10334           48 :         all_layers
   10335           48 :     }
   10336              : 
   10337              :     #[cfg(feature = "testing")]
   10338           44 :     fn check_layer_map_key_eq(
   10339           44 :         mut left: Vec<PersistentLayerKey>,
   10340           44 :         mut right: Vec<PersistentLayerKey>,
   10341           44 :     ) {
   10342           44 :         left.sort_by(sort_layer_key);
   10343           44 :         right.sort_by(sort_layer_key);
   10344           44 :         if left != right {
   10345            0 :             eprintln!("---LEFT---");
   10346            0 :             for left in left.iter() {
   10347            0 :                 eprintln!("{}", left);
   10348            0 :             }
   10349            0 :             eprintln!("---RIGHT---");
   10350            0 :             for right in right.iter() {
   10351            0 :                 eprintln!("{}", right);
   10352            0 :             }
   10353            0 :             assert_eq!(left, right);
   10354           44 :         }
   10355           44 :     }
   10356              : 
   10357              :     #[cfg(feature = "testing")]
   10358              :     #[tokio::test]
   10359            4 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   10360            4 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   10361            4 :         let (tenant, ctx) = harness.load().await;
   10362            4 : 
   10363          364 :         fn get_key(id: u32) -> Key {
   10364          364 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10365          364 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10366          364 :             key.field6 = id;
   10367          364 :             key
   10368          364 :         }
   10369            4 : 
   10370            4 :         // img layer at 0x10
   10371            4 :         let img_layer = (0..10)
   10372           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10373            4 :             .collect_vec();
   10374            4 : 
   10375            4 :         let delta1 = vec![
   10376            4 :             (
   10377            4 :                 get_key(1),
   10378            4 :                 Lsn(0x20),
   10379            4 :                 Value::Image(Bytes::from("value 1@0x20")),
   10380            4 :             ),
   10381            4 :             (
   10382            4 :                 get_key(2),
   10383            4 :                 Lsn(0x30),
   10384            4 :                 Value::Image(Bytes::from("value 2@0x30")),
   10385            4 :             ),
   10386            4 :             (
   10387            4 :                 get_key(3),
   10388            4 :                 Lsn(0x40),
   10389            4 :                 Value::Image(Bytes::from("value 3@0x40")),
   10390            4 :             ),
   10391            4 :         ];
   10392            4 :         let delta2 = vec![
   10393            4 :             (
   10394            4 :                 get_key(5),
   10395            4 :                 Lsn(0x20),
   10396            4 :                 Value::Image(Bytes::from("value 5@0x20")),
   10397            4 :             ),
   10398            4 :             (
   10399            4 :                 get_key(6),
   10400            4 :                 Lsn(0x20),
   10401            4 :                 Value::Image(Bytes::from("value 6@0x20")),
   10402            4 :             ),
   10403            4 :         ];
   10404            4 :         let delta3 = vec![
   10405            4 :             (
   10406            4 :                 get_key(8),
   10407            4 :                 Lsn(0x48),
   10408            4 :                 Value::Image(Bytes::from("value 8@0x48")),
   10409            4 :             ),
   10410            4 :             (
   10411            4 :                 get_key(9),
   10412            4 :                 Lsn(0x48),
   10413            4 :                 Value::Image(Bytes::from("value 9@0x48")),
   10414            4 :             ),
   10415            4 :         ];
   10416            4 : 
   10417            4 :         let tline = tenant
   10418            4 :             .create_test_timeline_with_layers(
   10419            4 :                 TIMELINE_ID,
   10420            4 :                 Lsn(0x10),
   10421            4 :                 DEFAULT_PG_VERSION,
   10422            4 :                 &ctx,
   10423            4 :                 vec![
   10424            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10425            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10426            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10427            4 :                 ], // delta layers
   10428            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10429            4 :                 Lsn(0x50),
   10430            4 :             )
   10431            4 :             .await?;
   10432            4 : 
   10433            4 :         {
   10434            4 :             tline
   10435            4 :                 .applied_gc_cutoff_lsn
   10436            4 :                 .lock_for_write()
   10437            4 :                 .store_and_unlock(Lsn(0x30))
   10438            4 :                 .wait()
   10439            4 :                 .await;
   10440            4 :             // Update GC info
   10441            4 :             let mut guard = tline.gc_info.write().unwrap();
   10442            4 :             *guard = GcInfo {
   10443            4 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   10444            4 :                 cutoffs: GcCutoffs {
   10445            4 :                     time: Lsn(0x30),
   10446            4 :                     space: Lsn(0x30),
   10447            4 :                 },
   10448            4 :                 leases: Default::default(),
   10449            4 :                 within_ancestor_pitr: false,
   10450            4 :             };
   10451            4 :         }
   10452            4 : 
   10453            4 :         let cancel = CancellationToken::new();
   10454            4 : 
   10455            4 :         // Do a partial compaction on key range 0..2
   10456            4 :         tline
   10457            4 :             .compact_with_gc(
   10458            4 :                 &cancel,
   10459            4 :                 CompactOptions {
   10460            4 :                     flags: EnumSet::new(),
   10461            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   10462            4 :                     ..Default::default()
   10463            4 :                 },
   10464            4 :                 &ctx,
   10465            4 :             )
   10466            4 :             .await
   10467            4 :             .unwrap();
   10468            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10469            4 :         check_layer_map_key_eq(
   10470            4 :             all_layers,
   10471            4 :             vec![
   10472            4 :                 // newly-generated image layer for the partial compaction range 0-2
   10473            4 :                 PersistentLayerKey {
   10474            4 :                     key_range: get_key(0)..get_key(2),
   10475            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10476            4 :                     is_delta: false,
   10477            4 :                 },
   10478            4 :                 PersistentLayerKey {
   10479            4 :                     key_range: get_key(0)..get_key(10),
   10480            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10481            4 :                     is_delta: false,
   10482            4 :                 },
   10483            4 :                 // delta1 is split and the second part is rewritten
   10484            4 :                 PersistentLayerKey {
   10485            4 :                     key_range: get_key(2)..get_key(4),
   10486            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10487            4 :                     is_delta: true,
   10488            4 :                 },
   10489            4 :                 PersistentLayerKey {
   10490            4 :                     key_range: get_key(5)..get_key(7),
   10491            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10492            4 :                     is_delta: true,
   10493            4 :                 },
   10494            4 :                 PersistentLayerKey {
   10495            4 :                     key_range: get_key(8)..get_key(10),
   10496            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10497            4 :                     is_delta: true,
   10498            4 :                 },
   10499            4 :             ],
   10500            4 :         );
   10501            4 : 
   10502            4 :         // Do a partial compaction on key range 2..4
   10503            4 :         tline
   10504            4 :             .compact_with_gc(
   10505            4 :                 &cancel,
   10506            4 :                 CompactOptions {
   10507            4 :                     flags: EnumSet::new(),
   10508            4 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   10509            4 :                     ..Default::default()
   10510            4 :                 },
   10511            4 :                 &ctx,
   10512            4 :             )
   10513            4 :             .await
   10514            4 :             .unwrap();
   10515            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10516            4 :         check_layer_map_key_eq(
   10517            4 :             all_layers,
   10518            4 :             vec![
   10519            4 :                 PersistentLayerKey {
   10520            4 :                     key_range: get_key(0)..get_key(2),
   10521            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10522            4 :                     is_delta: false,
   10523            4 :                 },
   10524            4 :                 PersistentLayerKey {
   10525            4 :                     key_range: get_key(0)..get_key(10),
   10526            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10527            4 :                     is_delta: false,
   10528            4 :                 },
   10529            4 :                 // image layer generated for the compaction range 2-4
   10530            4 :                 PersistentLayerKey {
   10531            4 :                     key_range: get_key(2)..get_key(4),
   10532            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10533            4 :                     is_delta: false,
   10534            4 :                 },
   10535            4 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   10536            4 :                 PersistentLayerKey {
   10537            4 :                     key_range: get_key(2)..get_key(4),
   10538            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10539            4 :                     is_delta: true,
   10540            4 :                 },
   10541            4 :                 PersistentLayerKey {
   10542            4 :                     key_range: get_key(5)..get_key(7),
   10543            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10544            4 :                     is_delta: true,
   10545            4 :                 },
   10546            4 :                 PersistentLayerKey {
   10547            4 :                     key_range: get_key(8)..get_key(10),
   10548            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10549            4 :                     is_delta: true,
   10550            4 :                 },
   10551            4 :             ],
   10552            4 :         );
   10553            4 : 
   10554            4 :         // Do a partial compaction on key range 4..9
   10555            4 :         tline
   10556            4 :             .compact_with_gc(
   10557            4 :                 &cancel,
   10558            4 :                 CompactOptions {
   10559            4 :                     flags: EnumSet::new(),
   10560            4 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   10561            4 :                     ..Default::default()
   10562            4 :                 },
   10563            4 :                 &ctx,
   10564            4 :             )
   10565            4 :             .await
   10566            4 :             .unwrap();
   10567            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10568            4 :         check_layer_map_key_eq(
   10569            4 :             all_layers,
   10570            4 :             vec![
   10571            4 :                 PersistentLayerKey {
   10572            4 :                     key_range: get_key(0)..get_key(2),
   10573            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10574            4 :                     is_delta: false,
   10575            4 :                 },
   10576            4 :                 PersistentLayerKey {
   10577            4 :                     key_range: get_key(0)..get_key(10),
   10578            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10579            4 :                     is_delta: false,
   10580            4 :                 },
   10581            4 :                 PersistentLayerKey {
   10582            4 :                     key_range: get_key(2)..get_key(4),
   10583            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10584            4 :                     is_delta: false,
   10585            4 :                 },
   10586            4 :                 PersistentLayerKey {
   10587            4 :                     key_range: get_key(2)..get_key(4),
   10588            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10589            4 :                     is_delta: true,
   10590            4 :                 },
   10591            4 :                 // image layer generated for this compaction range
   10592            4 :                 PersistentLayerKey {
   10593            4 :                     key_range: get_key(4)..get_key(9),
   10594            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10595            4 :                     is_delta: false,
   10596            4 :                 },
   10597            4 :                 PersistentLayerKey {
   10598            4 :                     key_range: get_key(8)..get_key(10),
   10599            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10600            4 :                     is_delta: true,
   10601            4 :                 },
   10602            4 :             ],
   10603            4 :         );
   10604            4 : 
   10605            4 :         // Do a partial compaction on key range 9..10
   10606            4 :         tline
   10607            4 :             .compact_with_gc(
   10608            4 :                 &cancel,
   10609            4 :                 CompactOptions {
   10610            4 :                     flags: EnumSet::new(),
   10611            4 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   10612            4 :                     ..Default::default()
   10613            4 :                 },
   10614            4 :                 &ctx,
   10615            4 :             )
   10616            4 :             .await
   10617            4 :             .unwrap();
   10618            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10619            4 :         check_layer_map_key_eq(
   10620            4 :             all_layers,
   10621            4 :             vec![
   10622            4 :                 PersistentLayerKey {
   10623            4 :                     key_range: get_key(0)..get_key(2),
   10624            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10625            4 :                     is_delta: false,
   10626            4 :                 },
   10627            4 :                 PersistentLayerKey {
   10628            4 :                     key_range: get_key(0)..get_key(10),
   10629            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10630            4 :                     is_delta: false,
   10631            4 :                 },
   10632            4 :                 PersistentLayerKey {
   10633            4 :                     key_range: get_key(2)..get_key(4),
   10634            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10635            4 :                     is_delta: false,
   10636            4 :                 },
   10637            4 :                 PersistentLayerKey {
   10638            4 :                     key_range: get_key(2)..get_key(4),
   10639            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10640            4 :                     is_delta: true,
   10641            4 :                 },
   10642            4 :                 PersistentLayerKey {
   10643            4 :                     key_range: get_key(4)..get_key(9),
   10644            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10645            4 :                     is_delta: false,
   10646            4 :                 },
   10647            4 :                 // image layer generated for the compaction range
   10648            4 :                 PersistentLayerKey {
   10649            4 :                     key_range: get_key(9)..get_key(10),
   10650            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10651            4 :                     is_delta: false,
   10652            4 :                 },
   10653            4 :                 PersistentLayerKey {
   10654            4 :                     key_range: get_key(8)..get_key(10),
   10655            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10656            4 :                     is_delta: true,
   10657            4 :                 },
   10658            4 :             ],
   10659            4 :         );
   10660            4 : 
   10661            4 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   10662            4 :         tline
   10663            4 :             .compact_with_gc(
   10664            4 :                 &cancel,
   10665            4 :                 CompactOptions {
   10666            4 :                     flags: EnumSet::new(),
   10667            4 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   10668            4 :                     ..Default::default()
   10669            4 :                 },
   10670            4 :                 &ctx,
   10671            4 :             )
   10672            4 :             .await
   10673            4 :             .unwrap();
   10674            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10675            4 :         check_layer_map_key_eq(
   10676            4 :             all_layers,
   10677            4 :             vec![
   10678            4 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   10679            4 :                 PersistentLayerKey {
   10680            4 :                     key_range: get_key(0)..get_key(10),
   10681            4 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   10682            4 :                     is_delta: false,
   10683            4 :                 },
   10684            4 :                 PersistentLayerKey {
   10685            4 :                     key_range: get_key(2)..get_key(4),
   10686            4 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   10687            4 :                     is_delta: true,
   10688            4 :                 },
   10689            4 :                 PersistentLayerKey {
   10690            4 :                     key_range: get_key(8)..get_key(10),
   10691            4 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   10692            4 :                     is_delta: true,
   10693            4 :                 },
   10694            4 :             ],
   10695            4 :         );
   10696            4 :         Ok(())
   10697            4 :     }
   10698              : 
   10699              :     #[cfg(feature = "testing")]
   10700              :     #[tokio::test]
   10701            4 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   10702            4 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   10703            4 :             .await
   10704            4 :             .unwrap();
   10705            4 :         let (tenant, ctx) = harness.load().await;
   10706            4 :         let tline_parent = tenant
   10707            4 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   10708            4 :             .await
   10709            4 :             .unwrap();
   10710            4 :         let tline_child = tenant
   10711            4 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   10712            4 :             .await
   10713            4 :             .unwrap();
   10714            4 :         {
   10715            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10716            4 :             assert_eq!(
   10717            4 :                 gc_info_parent.retain_lsns,
   10718            4 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   10719            4 :             );
   10720            4 :         }
   10721            4 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   10722            4 :         tline_child
   10723            4 :             .remote_client
   10724            4 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   10725            4 :             .unwrap();
   10726            4 :         tline_child.remote_client.wait_completion().await.unwrap();
   10727            4 :         offload_timeline(&tenant, &tline_child)
   10728            4 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   10729            4 :             .await.unwrap();
   10730            4 :         let child_timeline_id = tline_child.timeline_id;
   10731            4 :         Arc::try_unwrap(tline_child).unwrap();
   10732            4 : 
   10733            4 :         {
   10734            4 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   10735            4 :             assert_eq!(
   10736            4 :                 gc_info_parent.retain_lsns,
   10737            4 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   10738            4 :             );
   10739            4 :         }
   10740            4 : 
   10741            4 :         tenant
   10742            4 :             .get_offloaded_timeline(child_timeline_id)
   10743            4 :             .unwrap()
   10744            4 :             .defuse_for_tenant_drop();
   10745            4 : 
   10746            4 :         Ok(())
   10747            4 :     }
   10748              : 
   10749              :     #[cfg(feature = "testing")]
   10750              :     #[tokio::test]
   10751            4 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   10752            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   10753            4 :         let (tenant, ctx) = harness.load().await;
   10754            4 : 
   10755          592 :         fn get_key(id: u32) -> Key {
   10756          592 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10757          592 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10758          592 :             key.field6 = id;
   10759          592 :             key
   10760          592 :         }
   10761            4 : 
   10762            4 :         let img_layer = (0..10)
   10763           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10764            4 :             .collect_vec();
   10765            4 : 
   10766            4 :         let delta1 = vec![(
   10767            4 :             get_key(1),
   10768            4 :             Lsn(0x20),
   10769            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10770            4 :         )];
   10771            4 :         let delta4 = vec![(
   10772            4 :             get_key(1),
   10773            4 :             Lsn(0x28),
   10774            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10775            4 :         )];
   10776            4 :         let delta2 = vec![
   10777            4 :             (
   10778            4 :                 get_key(1),
   10779            4 :                 Lsn(0x30),
   10780            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10781            4 :             ),
   10782            4 :             (
   10783            4 :                 get_key(1),
   10784            4 :                 Lsn(0x38),
   10785            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10786            4 :             ),
   10787            4 :         ];
   10788            4 :         let delta3 = vec![
   10789            4 :             (
   10790            4 :                 get_key(8),
   10791            4 :                 Lsn(0x48),
   10792            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10793            4 :             ),
   10794            4 :             (
   10795            4 :                 get_key(9),
   10796            4 :                 Lsn(0x48),
   10797            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10798            4 :             ),
   10799            4 :         ];
   10800            4 : 
   10801            4 :         let tline = tenant
   10802            4 :             .create_test_timeline_with_layers(
   10803            4 :                 TIMELINE_ID,
   10804            4 :                 Lsn(0x10),
   10805            4 :                 DEFAULT_PG_VERSION,
   10806            4 :                 &ctx,
   10807            4 :                 vec![
   10808            4 :                     // delta1/2/4 only contain a single key but multiple updates
   10809            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   10810            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10811            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   10812            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   10813            4 :                 ], // delta layers
   10814            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10815            4 :                 Lsn(0x50),
   10816            4 :             )
   10817            4 :             .await?;
   10818            4 :         {
   10819            4 :             tline
   10820            4 :                 .applied_gc_cutoff_lsn
   10821            4 :                 .lock_for_write()
   10822            4 :                 .store_and_unlock(Lsn(0x30))
   10823            4 :                 .wait()
   10824            4 :                 .await;
   10825            4 :             // Update GC info
   10826            4 :             let mut guard = tline.gc_info.write().unwrap();
   10827            4 :             *guard = GcInfo {
   10828            4 :                 retain_lsns: vec![
   10829            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10830            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10831            4 :                 ],
   10832            4 :                 cutoffs: GcCutoffs {
   10833            4 :                     time: Lsn(0x30),
   10834            4 :                     space: Lsn(0x30),
   10835            4 :                 },
   10836            4 :                 leases: Default::default(),
   10837            4 :                 within_ancestor_pitr: false,
   10838            4 :             };
   10839            4 :         }
   10840            4 : 
   10841            4 :         let expected_result = [
   10842            4 :             Bytes::from_static(b"value 0@0x10"),
   10843            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10844            4 :             Bytes::from_static(b"value 2@0x10"),
   10845            4 :             Bytes::from_static(b"value 3@0x10"),
   10846            4 :             Bytes::from_static(b"value 4@0x10"),
   10847            4 :             Bytes::from_static(b"value 5@0x10"),
   10848            4 :             Bytes::from_static(b"value 6@0x10"),
   10849            4 :             Bytes::from_static(b"value 7@0x10"),
   10850            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10851            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10852            4 :         ];
   10853            4 : 
   10854            4 :         let expected_result_at_gc_horizon = [
   10855            4 :             Bytes::from_static(b"value 0@0x10"),
   10856            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10857            4 :             Bytes::from_static(b"value 2@0x10"),
   10858            4 :             Bytes::from_static(b"value 3@0x10"),
   10859            4 :             Bytes::from_static(b"value 4@0x10"),
   10860            4 :             Bytes::from_static(b"value 5@0x10"),
   10861            4 :             Bytes::from_static(b"value 6@0x10"),
   10862            4 :             Bytes::from_static(b"value 7@0x10"),
   10863            4 :             Bytes::from_static(b"value 8@0x10"),
   10864            4 :             Bytes::from_static(b"value 9@0x10"),
   10865            4 :         ];
   10866            4 : 
   10867            4 :         let expected_result_at_lsn_20 = [
   10868            4 :             Bytes::from_static(b"value 0@0x10"),
   10869            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10870            4 :             Bytes::from_static(b"value 2@0x10"),
   10871            4 :             Bytes::from_static(b"value 3@0x10"),
   10872            4 :             Bytes::from_static(b"value 4@0x10"),
   10873            4 :             Bytes::from_static(b"value 5@0x10"),
   10874            4 :             Bytes::from_static(b"value 6@0x10"),
   10875            4 :             Bytes::from_static(b"value 7@0x10"),
   10876            4 :             Bytes::from_static(b"value 8@0x10"),
   10877            4 :             Bytes::from_static(b"value 9@0x10"),
   10878            4 :         ];
   10879            4 : 
   10880            4 :         let expected_result_at_lsn_10 = [
   10881            4 :             Bytes::from_static(b"value 0@0x10"),
   10882            4 :             Bytes::from_static(b"value 1@0x10"),
   10883            4 :             Bytes::from_static(b"value 2@0x10"),
   10884            4 :             Bytes::from_static(b"value 3@0x10"),
   10885            4 :             Bytes::from_static(b"value 4@0x10"),
   10886            4 :             Bytes::from_static(b"value 5@0x10"),
   10887            4 :             Bytes::from_static(b"value 6@0x10"),
   10888            4 :             Bytes::from_static(b"value 7@0x10"),
   10889            4 :             Bytes::from_static(b"value 8@0x10"),
   10890            4 :             Bytes::from_static(b"value 9@0x10"),
   10891            4 :         ];
   10892            4 : 
   10893           12 :         let verify_result = || async {
   10894           12 :             let gc_horizon = {
   10895           12 :                 let gc_info = tline.gc_info.read().unwrap();
   10896           12 :                 gc_info.cutoffs.time
   10897            4 :             };
   10898          132 :             for idx in 0..10 {
   10899          120 :                 assert_eq!(
   10900          120 :                     tline
   10901          120 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10902          120 :                         .await
   10903          120 :                         .unwrap(),
   10904          120 :                     &expected_result[idx]
   10905            4 :                 );
   10906          120 :                 assert_eq!(
   10907          120 :                     tline
   10908          120 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10909          120 :                         .await
   10910          120 :                         .unwrap(),
   10911          120 :                     &expected_result_at_gc_horizon[idx]
   10912            4 :                 );
   10913          120 :                 assert_eq!(
   10914          120 :                     tline
   10915          120 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10916          120 :                         .await
   10917          120 :                         .unwrap(),
   10918          120 :                     &expected_result_at_lsn_20[idx]
   10919            4 :                 );
   10920          120 :                 assert_eq!(
   10921          120 :                     tline
   10922          120 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10923          120 :                         .await
   10924          120 :                         .unwrap(),
   10925          120 :                     &expected_result_at_lsn_10[idx]
   10926            4 :                 );
   10927            4 :             }
   10928           24 :         };
   10929            4 : 
   10930            4 :         verify_result().await;
   10931            4 : 
   10932            4 :         let cancel = CancellationToken::new();
   10933            4 :         tline
   10934            4 :             .compact_with_gc(
   10935            4 :                 &cancel,
   10936            4 :                 CompactOptions {
   10937            4 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   10938            4 :                     ..Default::default()
   10939            4 :                 },
   10940            4 :                 &ctx,
   10941            4 :             )
   10942            4 :             .await
   10943            4 :             .unwrap();
   10944            4 :         verify_result().await;
   10945            4 : 
   10946            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10947            4 :         check_layer_map_key_eq(
   10948            4 :             all_layers,
   10949            4 :             vec![
   10950            4 :                 // The original image layer, not compacted
   10951            4 :                 PersistentLayerKey {
   10952            4 :                     key_range: get_key(0)..get_key(10),
   10953            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10954            4 :                     is_delta: false,
   10955            4 :                 },
   10956            4 :                 // Delta layer below the specified above_lsn not compacted
   10957            4 :                 PersistentLayerKey {
   10958            4 :                     key_range: get_key(1)..get_key(2),
   10959            4 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   10960            4 :                     is_delta: true,
   10961            4 :                 },
   10962            4 :                 // Delta layer compacted above the LSN
   10963            4 :                 PersistentLayerKey {
   10964            4 :                     key_range: get_key(1)..get_key(10),
   10965            4 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   10966            4 :                     is_delta: true,
   10967            4 :                 },
   10968            4 :             ],
   10969            4 :         );
   10970            4 : 
   10971            4 :         // compact again
   10972            4 :         tline
   10973            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10974            4 :             .await
   10975            4 :             .unwrap();
   10976            4 :         verify_result().await;
   10977            4 : 
   10978            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   10979            4 :         check_layer_map_key_eq(
   10980            4 :             all_layers,
   10981            4 :             vec![
   10982            4 :                 // The compacted image layer (full key range)
   10983            4 :                 PersistentLayerKey {
   10984            4 :                     key_range: Key::MIN..Key::MAX,
   10985            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   10986            4 :                     is_delta: false,
   10987            4 :                 },
   10988            4 :                 // All other data in the delta layer
   10989            4 :                 PersistentLayerKey {
   10990            4 :                     key_range: get_key(1)..get_key(10),
   10991            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   10992            4 :                     is_delta: true,
   10993            4 :                 },
   10994            4 :             ],
   10995            4 :         );
   10996            4 : 
   10997            4 :         Ok(())
   10998            4 :     }
   10999              : 
   11000              :     #[cfg(feature = "testing")]
   11001              :     #[tokio::test]
   11002            4 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   11003            4 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   11004            4 :         let (tenant, ctx) = harness.load().await;
   11005            4 : 
   11006         1016 :         fn get_key(id: u32) -> Key {
   11007         1016 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11008         1016 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11009         1016 :             key.field6 = id;
   11010         1016 :             key
   11011         1016 :         }
   11012            4 : 
   11013            4 :         let img_layer = (0..10)
   11014           40 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11015            4 :             .collect_vec();
   11016            4 : 
   11017            4 :         let delta1 = vec![(
   11018            4 :             get_key(1),
   11019            4 :             Lsn(0x20),
   11020            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11021            4 :         )];
   11022            4 :         let delta4 = vec![(
   11023            4 :             get_key(1),
   11024            4 :             Lsn(0x28),
   11025            4 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11026            4 :         )];
   11027            4 :         let delta2 = vec![
   11028            4 :             (
   11029            4 :                 get_key(1),
   11030            4 :                 Lsn(0x30),
   11031            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11032            4 :             ),
   11033            4 :             (
   11034            4 :                 get_key(1),
   11035            4 :                 Lsn(0x38),
   11036            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11037            4 :             ),
   11038            4 :         ];
   11039            4 :         let delta3 = vec![
   11040            4 :             (
   11041            4 :                 get_key(8),
   11042            4 :                 Lsn(0x48),
   11043            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11044            4 :             ),
   11045            4 :             (
   11046            4 :                 get_key(9),
   11047            4 :                 Lsn(0x48),
   11048            4 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11049            4 :             ),
   11050            4 :         ];
   11051            4 : 
   11052            4 :         let tline = tenant
   11053            4 :             .create_test_timeline_with_layers(
   11054            4 :                 TIMELINE_ID,
   11055            4 :                 Lsn(0x10),
   11056            4 :                 DEFAULT_PG_VERSION,
   11057            4 :                 &ctx,
   11058            4 :                 vec![
   11059            4 :                     // delta1/2/4 only contain a single key but multiple updates
   11060            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11061            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11062            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11063            4 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11064            4 :                 ], // delta layers
   11065            4 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11066            4 :                 Lsn(0x50),
   11067            4 :             )
   11068            4 :             .await?;
   11069            4 :         {
   11070            4 :             tline
   11071            4 :                 .applied_gc_cutoff_lsn
   11072            4 :                 .lock_for_write()
   11073            4 :                 .store_and_unlock(Lsn(0x30))
   11074            4 :                 .wait()
   11075            4 :                 .await;
   11076            4 :             // Update GC info
   11077            4 :             let mut guard = tline.gc_info.write().unwrap();
   11078            4 :             *guard = GcInfo {
   11079            4 :                 retain_lsns: vec![
   11080            4 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11081            4 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11082            4 :                 ],
   11083            4 :                 cutoffs: GcCutoffs {
   11084            4 :                     time: Lsn(0x30),
   11085            4 :                     space: Lsn(0x30),
   11086            4 :                 },
   11087            4 :                 leases: Default::default(),
   11088            4 :                 within_ancestor_pitr: false,
   11089            4 :             };
   11090            4 :         }
   11091            4 : 
   11092            4 :         let expected_result = [
   11093            4 :             Bytes::from_static(b"value 0@0x10"),
   11094            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11095            4 :             Bytes::from_static(b"value 2@0x10"),
   11096            4 :             Bytes::from_static(b"value 3@0x10"),
   11097            4 :             Bytes::from_static(b"value 4@0x10"),
   11098            4 :             Bytes::from_static(b"value 5@0x10"),
   11099            4 :             Bytes::from_static(b"value 6@0x10"),
   11100            4 :             Bytes::from_static(b"value 7@0x10"),
   11101            4 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11102            4 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11103            4 :         ];
   11104            4 : 
   11105            4 :         let expected_result_at_gc_horizon = [
   11106            4 :             Bytes::from_static(b"value 0@0x10"),
   11107            4 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11108            4 :             Bytes::from_static(b"value 2@0x10"),
   11109            4 :             Bytes::from_static(b"value 3@0x10"),
   11110            4 :             Bytes::from_static(b"value 4@0x10"),
   11111            4 :             Bytes::from_static(b"value 5@0x10"),
   11112            4 :             Bytes::from_static(b"value 6@0x10"),
   11113            4 :             Bytes::from_static(b"value 7@0x10"),
   11114            4 :             Bytes::from_static(b"value 8@0x10"),
   11115            4 :             Bytes::from_static(b"value 9@0x10"),
   11116            4 :         ];
   11117            4 : 
   11118            4 :         let expected_result_at_lsn_20 = [
   11119            4 :             Bytes::from_static(b"value 0@0x10"),
   11120            4 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11121            4 :             Bytes::from_static(b"value 2@0x10"),
   11122            4 :             Bytes::from_static(b"value 3@0x10"),
   11123            4 :             Bytes::from_static(b"value 4@0x10"),
   11124            4 :             Bytes::from_static(b"value 5@0x10"),
   11125            4 :             Bytes::from_static(b"value 6@0x10"),
   11126            4 :             Bytes::from_static(b"value 7@0x10"),
   11127            4 :             Bytes::from_static(b"value 8@0x10"),
   11128            4 :             Bytes::from_static(b"value 9@0x10"),
   11129            4 :         ];
   11130            4 : 
   11131            4 :         let expected_result_at_lsn_10 = [
   11132            4 :             Bytes::from_static(b"value 0@0x10"),
   11133            4 :             Bytes::from_static(b"value 1@0x10"),
   11134            4 :             Bytes::from_static(b"value 2@0x10"),
   11135            4 :             Bytes::from_static(b"value 3@0x10"),
   11136            4 :             Bytes::from_static(b"value 4@0x10"),
   11137            4 :             Bytes::from_static(b"value 5@0x10"),
   11138            4 :             Bytes::from_static(b"value 6@0x10"),
   11139            4 :             Bytes::from_static(b"value 7@0x10"),
   11140            4 :             Bytes::from_static(b"value 8@0x10"),
   11141            4 :             Bytes::from_static(b"value 9@0x10"),
   11142            4 :         ];
   11143            4 : 
   11144           20 :         let verify_result = || async {
   11145           20 :             let gc_horizon = {
   11146           20 :                 let gc_info = tline.gc_info.read().unwrap();
   11147           20 :                 gc_info.cutoffs.time
   11148            4 :             };
   11149          220 :             for idx in 0..10 {
   11150          200 :                 assert_eq!(
   11151          200 :                     tline
   11152          200 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11153          200 :                         .await
   11154          200 :                         .unwrap(),
   11155          200 :                     &expected_result[idx]
   11156            4 :                 );
   11157          200 :                 assert_eq!(
   11158          200 :                     tline
   11159          200 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11160          200 :                         .await
   11161          200 :                         .unwrap(),
   11162          200 :                     &expected_result_at_gc_horizon[idx]
   11163            4 :                 );
   11164          200 :                 assert_eq!(
   11165          200 :                     tline
   11166          200 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11167          200 :                         .await
   11168          200 :                         .unwrap(),
   11169          200 :                     &expected_result_at_lsn_20[idx]
   11170            4 :                 );
   11171          200 :                 assert_eq!(
   11172          200 :                     tline
   11173          200 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11174          200 :                         .await
   11175          200 :                         .unwrap(),
   11176          200 :                     &expected_result_at_lsn_10[idx]
   11177            4 :                 );
   11178            4 :             }
   11179           40 :         };
   11180            4 : 
   11181            4 :         verify_result().await;
   11182            4 : 
   11183            4 :         let cancel = CancellationToken::new();
   11184            4 : 
   11185            4 :         tline
   11186            4 :             .compact_with_gc(
   11187            4 :                 &cancel,
   11188            4 :                 CompactOptions {
   11189            4 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11190            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   11191            4 :                     ..Default::default()
   11192            4 :                 },
   11193            4 :                 &ctx,
   11194            4 :             )
   11195            4 :             .await
   11196            4 :             .unwrap();
   11197            4 :         verify_result().await;
   11198            4 : 
   11199            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11200            4 :         check_layer_map_key_eq(
   11201            4 :             all_layers,
   11202            4 :             vec![
   11203            4 :                 // The original image layer, not compacted
   11204            4 :                 PersistentLayerKey {
   11205            4 :                     key_range: get_key(0)..get_key(10),
   11206            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11207            4 :                     is_delta: false,
   11208            4 :                 },
   11209            4 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   11210            4 :                 // the layer 0x28-0x30 into one.
   11211            4 :                 PersistentLayerKey {
   11212            4 :                     key_range: get_key(1)..get_key(2),
   11213            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11214            4 :                     is_delta: true,
   11215            4 :                 },
   11216            4 :                 // Above the upper bound and untouched
   11217            4 :                 PersistentLayerKey {
   11218            4 :                     key_range: get_key(1)..get_key(2),
   11219            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11220            4 :                     is_delta: true,
   11221            4 :                 },
   11222            4 :                 // This layer is untouched
   11223            4 :                 PersistentLayerKey {
   11224            4 :                     key_range: get_key(8)..get_key(10),
   11225            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11226            4 :                     is_delta: true,
   11227            4 :                 },
   11228            4 :             ],
   11229            4 :         );
   11230            4 : 
   11231            4 :         tline
   11232            4 :             .compact_with_gc(
   11233            4 :                 &cancel,
   11234            4 :                 CompactOptions {
   11235            4 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   11236            4 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   11237            4 :                     ..Default::default()
   11238            4 :                 },
   11239            4 :                 &ctx,
   11240            4 :             )
   11241            4 :             .await
   11242            4 :             .unwrap();
   11243            4 :         verify_result().await;
   11244            4 : 
   11245            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11246            4 :         check_layer_map_key_eq(
   11247            4 :             all_layers,
   11248            4 :             vec![
   11249            4 :                 // The original image layer, not compacted
   11250            4 :                 PersistentLayerKey {
   11251            4 :                     key_range: get_key(0)..get_key(10),
   11252            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11253            4 :                     is_delta: false,
   11254            4 :                 },
   11255            4 :                 // Not in the compaction key range, uncompacted
   11256            4 :                 PersistentLayerKey {
   11257            4 :                     key_range: get_key(1)..get_key(2),
   11258            4 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   11259            4 :                     is_delta: true,
   11260            4 :                 },
   11261            4 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   11262            4 :                 PersistentLayerKey {
   11263            4 :                     key_range: get_key(1)..get_key(2),
   11264            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11265            4 :                     is_delta: true,
   11266            4 :                 },
   11267            4 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   11268            4 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   11269            4 :                 // becomes 0x50.
   11270            4 :                 PersistentLayerKey {
   11271            4 :                     key_range: get_key(8)..get_key(10),
   11272            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11273            4 :                     is_delta: true,
   11274            4 :                 },
   11275            4 :             ],
   11276            4 :         );
   11277            4 : 
   11278            4 :         // compact again
   11279            4 :         tline
   11280            4 :             .compact_with_gc(
   11281            4 :                 &cancel,
   11282            4 :                 CompactOptions {
   11283            4 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   11284            4 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   11285            4 :                     ..Default::default()
   11286            4 :                 },
   11287            4 :                 &ctx,
   11288            4 :             )
   11289            4 :             .await
   11290            4 :             .unwrap();
   11291            4 :         verify_result().await;
   11292            4 : 
   11293            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11294            4 :         check_layer_map_key_eq(
   11295            4 :             all_layers,
   11296            4 :             vec![
   11297            4 :                 // The original image layer, not compacted
   11298            4 :                 PersistentLayerKey {
   11299            4 :                     key_range: get_key(0)..get_key(10),
   11300            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11301            4 :                     is_delta: false,
   11302            4 :                 },
   11303            4 :                 // The range gets compacted
   11304            4 :                 PersistentLayerKey {
   11305            4 :                     key_range: get_key(1)..get_key(2),
   11306            4 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   11307            4 :                     is_delta: true,
   11308            4 :                 },
   11309            4 :                 // Not touched during this iteration of compaction
   11310            4 :                 PersistentLayerKey {
   11311            4 :                     key_range: get_key(8)..get_key(10),
   11312            4 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   11313            4 :                     is_delta: true,
   11314            4 :                 },
   11315            4 :             ],
   11316            4 :         );
   11317            4 : 
   11318            4 :         // final full compaction
   11319            4 :         tline
   11320            4 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11321            4 :             .await
   11322            4 :             .unwrap();
   11323            4 :         verify_result().await;
   11324            4 : 
   11325            4 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11326            4 :         check_layer_map_key_eq(
   11327            4 :             all_layers,
   11328            4 :             vec![
   11329            4 :                 // The compacted image layer (full key range)
   11330            4 :                 PersistentLayerKey {
   11331            4 :                     key_range: Key::MIN..Key::MAX,
   11332            4 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11333            4 :                     is_delta: false,
   11334            4 :                 },
   11335            4 :                 // All other data in the delta layer
   11336            4 :                 PersistentLayerKey {
   11337            4 :                     key_range: get_key(1)..get_key(10),
   11338            4 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11339            4 :                     is_delta: true,
   11340            4 :                 },
   11341            4 :             ],
   11342            4 :         );
   11343            4 : 
   11344            4 :         Ok(())
   11345            4 :     }
   11346              : }
        

Generated by: LCOV version 2.1-beta