LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 2620485e474b48c32427149a5d91ef8fc2cd649e.info Lines: 78.5 % 9610 7541
Test Date: 2025-05-01 22:50:11 Functions: 62.3 % 470 293

            Line data    Source code
       1              : //! Timeline repository implementation that keeps old data in layer files, and
       2              : //! the recent changes in ephemeral files.
       3              : //!
       4              : //! See tenant/*_layer.rs files. The functions here are responsible for locating
       5              : //! the correct layer for the get/put call, walking back the timeline branching
       6              : //! history as needed.
       7              : //!
       8              : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
       9              : //! directory. See docs/pageserver-storage.md for how the files are managed.
      10              : //! In addition to the layer files, there is a metadata file in the same
      11              : //! directory that contains information about the timeline, in particular its
      12              : //! parent timeline, and the last LSN that has been written to disk.
      13              : //!
      14              : 
      15              : use std::collections::hash_map::Entry;
      16              : use std::collections::{BTreeMap, HashMap, HashSet};
      17              : use std::fmt::{Debug, Display};
      18              : use std::fs::File;
      19              : use std::future::Future;
      20              : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
      21              : use std::sync::{Arc, Mutex, Weak};
      22              : use std::time::{Duration, Instant, SystemTime};
      23              : use std::{fmt, fs};
      24              : 
      25              : use anyhow::{Context, bail};
      26              : use arc_swap::ArcSwap;
      27              : use camino::{Utf8Path, Utf8PathBuf};
      28              : use chrono::NaiveDateTime;
      29              : use enumset::EnumSet;
      30              : use futures::StreamExt;
      31              : use futures::stream::FuturesUnordered;
      32              : use itertools::Itertools as _;
      33              : use once_cell::sync::Lazy;
      34              : pub use pageserver_api::models::TenantState;
      35              : use pageserver_api::models::{self, RelSizeMigration};
      36              : use pageserver_api::models::{
      37              :     CompactInfoResponse, LsnLease, TimelineArchivalState, TimelineState, TopTenantShardItem,
      38              :     WalRedoManagerStatus,
      39              : };
      40              : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
      41              : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
      42              : use remote_timeline_client::index::GcCompactionState;
      43              : use remote_timeline_client::manifest::{
      44              :     LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
      45              : };
      46              : use remote_timeline_client::{
      47              :     FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
      48              :     download_tenant_manifest,
      49              : };
      50              : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
      51              : use storage_broker::BrokerClientChannel;
      52              : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
      53              : use timeline::offload::{OffloadError, offload_timeline};
      54              : use timeline::{
      55              :     CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
      56              : };
      57              : use tokio::io::BufReader;
      58              : use tokio::sync::{Notify, Semaphore, watch};
      59              : use tokio::task::JoinSet;
      60              : use tokio_util::sync::CancellationToken;
      61              : use tracing::*;
      62              : use upload_queue::NotInitialized;
      63              : use utils::circuit_breaker::CircuitBreaker;
      64              : use utils::crashsafe::path_with_suffix_extension;
      65              : use utils::sync::gate::{Gate, GateGuard};
      66              : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
      67              : use utils::try_rcu::ArcSwapExt;
      68              : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
      69              : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
      70              : 
      71              : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf};
      72              : use self::metadata::TimelineMetadata;
      73              : use self::mgr::{GetActiveTenantError, GetTenantError};
      74              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      75              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      76              : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
      77              : use self::timeline::{
      78              :     EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
      79              : };
      80              : use crate::config::PageServerConf;
      81              : use crate::context;
      82              : use crate::context::RequestContextBuilder;
      83              : use crate::context::{DownloadBehavior, RequestContext};
      84              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
      85              : use crate::l0_flush::L0FlushGlobalState;
      86              : use crate::metrics::{
      87              :     BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
      88              :     INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_STATE_METRIC,
      89              :     TENANT_SYNTHETIC_SIZE_METRIC, remove_tenant_metrics,
      90              : };
      91              : use crate::task_mgr::TaskKind;
      92              : use crate::tenant::config::LocationMode;
      93              : use crate::tenant::gc_result::GcResult;
      94              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
      95              : use crate::tenant::remote_timeline_client::{
      96              :     INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
      97              : };
      98              : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
      99              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     100              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     101              : use crate::virtual_file::VirtualFile;
     102              : use crate::walingest::WalLagCooldown;
     103              : use crate::walredo::{PostgresRedoManager, RedoAttemptType};
     104              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
     105              : 
     106            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     107              : use utils::crashsafe;
     108              : use utils::generation::Generation;
     109              : use utils::id::TimelineId;
     110              : use utils::lsn::{Lsn, RecordLsn};
     111              : 
     112              : pub mod blob_io;
     113              : pub mod block_io;
     114              : pub mod vectored_blob_io;
     115              : 
     116              : pub mod disk_btree;
     117              : pub(crate) mod ephemeral_file;
     118              : pub mod layer_map;
     119              : 
     120              : pub mod metadata;
     121              : pub mod remote_timeline_client;
     122              : pub mod storage_layer;
     123              : 
     124              : pub mod checks;
     125              : pub mod config;
     126              : pub mod mgr;
     127              : pub mod secondary;
     128              : pub mod tasks;
     129              : pub mod upload_queue;
     130              : 
     131              : pub(crate) mod timeline;
     132              : 
     133              : pub mod size;
     134              : 
     135              : mod gc_block;
     136              : mod gc_result;
     137              : pub(crate) mod throttle;
     138              : 
     139              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     140              : 
     141              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     142              : // re-export for use in walreceiver
     143              : pub use crate::tenant::timeline::WalReceiverInfo;
     144              : 
     145              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     146              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     147              : 
     148              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     149              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     150              : 
     151              : /// References to shared objects that are passed into each tenant, such
     152              : /// as the shared remote storage client and process initialization state.
     153              : #[derive(Clone)]
     154              : pub struct TenantSharedResources {
     155              :     pub broker_client: storage_broker::BrokerClientChannel,
     156              :     pub remote_storage: GenericRemoteStorage,
     157              :     pub deletion_queue_client: DeletionQueueClient,
     158              :     pub l0_flush_global_state: L0FlushGlobalState,
     159              : }
     160              : 
     161              : /// A [`TenantShard`] is really an _attached_ tenant.  The configuration
     162              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     163              : /// in this struct.
     164              : #[derive(Clone)]
     165              : pub(super) struct AttachedTenantConf {
     166              :     tenant_conf: pageserver_api::models::TenantConfig,
     167              :     location: AttachedLocationConfig,
     168              :     /// The deadline before which we are blocked from GC so that
     169              :     /// leases have a chance to be renewed.
     170              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     171              : }
     172              : 
     173              : impl AttachedTenantConf {
     174         1404 :     fn new(
     175         1404 :         tenant_conf: pageserver_api::models::TenantConfig,
     176         1404 :         location: AttachedLocationConfig,
     177         1404 :     ) -> Self {
     178              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     179              :         //
     180              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     181              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     182              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     183         1404 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     184         1404 :             Some(
     185         1404 :                 tokio::time::Instant::now()
     186         1404 :                     + tenant_conf
     187         1404 :                         .lsn_lease_length
     188         1404 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     189         1404 :             )
     190              :         } else {
     191              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     192              :             // because we don't do GC in these modes.
     193            0 :             None
     194              :         };
     195              : 
     196         1404 :         Self {
     197         1404 :             tenant_conf,
     198         1404 :             location,
     199         1404 :             lsn_lease_deadline,
     200         1404 :         }
     201         1404 :     }
     202              : 
     203         1404 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     204         1404 :         match &location_conf.mode {
     205         1404 :             LocationMode::Attached(attach_conf) => {
     206         1404 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     207              :             }
     208              :             LocationMode::Secondary(_) => {
     209            0 :                 anyhow::bail!(
     210            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     211            0 :                 )
     212              :             }
     213              :         }
     214         1404 :     }
     215              : 
     216         4572 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     217         4572 :         self.lsn_lease_deadline
     218         4572 :             .map(|d| tokio::time::Instant::now() < d)
     219         4572 :             .unwrap_or(false)
     220         4572 :     }
     221              : }
     222              : struct TimelinePreload {
     223              :     timeline_id: TimelineId,
     224              :     client: RemoteTimelineClient,
     225              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     226              :     previous_heatmap: Option<PreviousHeatmap>,
     227              : }
     228              : 
     229              : pub(crate) struct TenantPreload {
     230              :     /// The tenant manifest from remote storage, or None if no manifest was found.
     231              :     tenant_manifest: Option<TenantManifest>,
     232              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     233              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     234              : }
     235              : 
     236              : /// When we spawn a tenant, there is a special mode for tenant creation that
     237              : /// avoids trying to read anything from remote storage.
     238              : pub(crate) enum SpawnMode {
     239              :     /// Activate as soon as possible
     240              :     Eager,
     241              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     242              :     Lazy,
     243              : }
     244              : 
     245              : ///
     246              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     247              : ///
     248              : pub struct TenantShard {
     249              :     // Global pageserver config parameters
     250              :     pub conf: &'static PageServerConf,
     251              : 
     252              :     /// The value creation timestamp, used to measure activation delay, see:
     253              :     /// <https://github.com/neondatabase/neon/issues/4025>
     254              :     constructed_at: Instant,
     255              : 
     256              :     state: watch::Sender<TenantState>,
     257              : 
     258              :     // Overridden tenant-specific config parameters.
     259              :     // We keep pageserver_api::models::TenantConfig sturct here to preserve the information
     260              :     // about parameters that are not set.
     261              :     // This is necessary to allow global config updates.
     262              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     263              : 
     264              :     tenant_shard_id: TenantShardId,
     265              : 
     266              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     267              :     shard_identity: ShardIdentity,
     268              : 
     269              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     270              :     /// Does not change over the lifetime of the [`TenantShard`] object.
     271              :     ///
     272              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     273              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     274              :     generation: Generation,
     275              : 
     276              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     277              : 
     278              :     /// During timeline creation, we first insert the TimelineId to the
     279              :     /// creating map, then `timelines`, then remove it from the creating map.
     280              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     281              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     282              : 
     283              :     /// Possibly offloaded and archived timelines
     284              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     285              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     286              : 
     287              :     /// The last tenant manifest known to be in remote storage. None if the manifest has not yet
     288              :     /// been either downloaded or uploaded. Always Some after tenant attach.
     289              :     ///
     290              :     /// Initially populated during tenant attach, updated via `maybe_upload_tenant_manifest`.
     291              :     ///
     292              :     /// Do not modify this directly. It is used to check whether a new manifest needs to be
     293              :     /// uploaded. The manifest is constructed in `build_tenant_manifest`, and uploaded via
     294              :     /// `maybe_upload_tenant_manifest`.
     295              :     remote_tenant_manifest: tokio::sync::Mutex<Option<TenantManifest>>,
     296              : 
     297              :     // This mutex prevents creation of new timelines during GC.
     298              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     299              :     // `timelines` mutex during all GC iteration
     300              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     301              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     302              :     // timeout...
     303              :     gc_cs: tokio::sync::Mutex<()>,
     304              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     305              : 
     306              :     // provides access to timeline data sitting in the remote storage
     307              :     pub(crate) remote_storage: GenericRemoteStorage,
     308              : 
     309              :     // Access to global deletion queue for when this tenant wants to schedule a deletion
     310              :     deletion_queue_client: DeletionQueueClient,
     311              : 
     312              :     /// Cached logical sizes updated updated on each [`TenantShard::gather_size_inputs`].
     313              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     314              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     315              : 
     316              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     317              : 
     318              :     /// Track repeated failures to compact, so that we can back off.
     319              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     320              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     321              : 
     322              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     323              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     324              : 
     325              :     /// Scheduled gc-compaction tasks.
     326              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     327              : 
     328              :     /// If the tenant is in Activating state, notify this to encourage it
     329              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     330              :     /// background warmup.
     331              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     332              : 
     333              :     /// Time it took for the tenant to activate. Zero if not active yet.
     334              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     335              : 
     336              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     337              :     // Timelines' cancellation token.
     338              :     pub(crate) cancel: CancellationToken,
     339              : 
     340              :     // Users of the TenantShard such as the page service must take this Gate to avoid
     341              :     // trying to use a TenantShard which is shutting down.
     342              :     pub(crate) gate: Gate,
     343              : 
     344              :     /// Throttle applied at the top of [`Timeline::get`].
     345              :     /// All [`TenantShard::timelines`] of a given [`TenantShard`] instance share the same [`throttle::Throttle`] instance.
     346              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     347              : 
     348              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     349              : 
     350              :     /// An ongoing timeline detach concurrency limiter.
     351              :     ///
     352              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     353              :     /// to have two running at the same time. A different one can be started if an earlier one
     354              :     /// has failed for whatever reason.
     355              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     356              : 
     357              :     /// `index_part.json` based gc blocking reason tracking.
     358              :     ///
     359              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     360              :     /// proceeding.
     361              :     pub(crate) gc_block: gc_block::GcBlock,
     362              : 
     363              :     l0_flush_global_state: L0FlushGlobalState,
     364              : }
     365              : impl std::fmt::Debug for TenantShard {
     366            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     367            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     368            0 :     }
     369              : }
     370              : 
     371              : pub(crate) enum WalRedoManager {
     372              :     Prod(WalredoManagerId, PostgresRedoManager),
     373              :     #[cfg(test)]
     374              :     Test(harness::TestRedoManager),
     375              : }
     376              : 
     377              : #[derive(thiserror::Error, Debug)]
     378              : #[error("pageserver is shutting down")]
     379              : pub(crate) struct GlobalShutDown;
     380              : 
     381              : impl WalRedoManager {
     382            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     383            0 :         let id = WalredoManagerId::next();
     384            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     385            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     386            0 :         match &mut *guard {
     387            0 :             Some(map) => {
     388            0 :                 map.insert(id, Arc::downgrade(&arc));
     389            0 :                 Ok(arc)
     390              :             }
     391            0 :             None => Err(GlobalShutDown),
     392              :         }
     393            0 :     }
     394              : }
     395              : 
     396              : impl Drop for WalRedoManager {
     397           60 :     fn drop(&mut self) {
     398           60 :         match self {
     399            0 :             Self::Prod(id, _) => {
     400            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     401            0 :                 if let Some(map) = &mut *guard {
     402            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     403            0 :                 }
     404              :             }
     405              :             #[cfg(test)]
     406           60 :             Self::Test(_) => {
     407           60 :                 // Not applicable to test redo manager
     408           60 :             }
     409              :         }
     410           60 :     }
     411              : }
     412              : 
     413              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     414              : /// the walredo processes outside of the regular order.
     415              : ///
     416              : /// This is necessary to work around a systemd bug where it freezes if there are
     417              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     418              : #[allow(clippy::type_complexity)]
     419              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     420              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     421            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     422              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     423              : pub(crate) struct WalredoManagerId(u64);
     424              : impl WalredoManagerId {
     425            0 :     pub fn next() -> Self {
     426              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     427            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     428            0 :         if id == 0 {
     429            0 :             panic!(
     430            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     431            0 :             );
     432            0 :         }
     433            0 :         Self(id)
     434            0 :     }
     435              : }
     436              : 
     437              : #[cfg(test)]
     438              : impl From<harness::TestRedoManager> for WalRedoManager {
     439         1404 :     fn from(mgr: harness::TestRedoManager) -> Self {
     440         1404 :         Self::Test(mgr)
     441         1404 :     }
     442              : }
     443              : 
     444              : impl WalRedoManager {
     445           36 :     pub(crate) async fn shutdown(&self) -> bool {
     446           36 :         match self {
     447            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     448              :             #[cfg(test)]
     449              :             Self::Test(_) => {
     450              :                 // Not applicable to test redo manager
     451           36 :                 true
     452              :             }
     453              :         }
     454           36 :     }
     455              : 
     456            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     457            0 :         match self {
     458            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     459            0 :             #[cfg(test)]
     460            0 :             Self::Test(_) => {
     461            0 :                 // Not applicable to test redo manager
     462            0 :             }
     463            0 :         }
     464            0 :     }
     465              : 
     466              :     /// # Cancel-Safety
     467              :     ///
     468              :     /// This method is cancellation-safe.
     469       321288 :     pub async fn request_redo(
     470       321288 :         &self,
     471       321288 :         key: pageserver_api::key::Key,
     472       321288 :         lsn: Lsn,
     473       321288 :         base_img: Option<(Lsn, bytes::Bytes)>,
     474       321288 :         records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
     475       321288 :         pg_version: u32,
     476       321288 :         redo_attempt_type: RedoAttemptType,
     477       321288 :     ) -> Result<bytes::Bytes, walredo::Error> {
     478       321288 :         match self {
     479            0 :             Self::Prod(_, mgr) => {
     480            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     481            0 :                     .await
     482              :             }
     483              :             #[cfg(test)]
     484       321288 :             Self::Test(mgr) => {
     485       321288 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     486       321288 :                     .await
     487              :             }
     488              :         }
     489       321288 :     }
     490              : 
     491            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     492            0 :         match self {
     493            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     494            0 :             #[cfg(test)]
     495            0 :             WalRedoManager::Test(_) => None,
     496            0 :         }
     497            0 :     }
     498              : }
     499              : 
     500              : /// A very lightweight memory representation of an offloaded timeline.
     501              : ///
     502              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     503              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     504              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     505              : /// more offloaded timelines than we can manage ones that aren't.
     506              : pub struct OffloadedTimeline {
     507              :     pub tenant_shard_id: TenantShardId,
     508              :     pub timeline_id: TimelineId,
     509              :     pub ancestor_timeline_id: Option<TimelineId>,
     510              :     /// Whether to retain the branch lsn at the ancestor or not
     511              :     pub ancestor_retain_lsn: Option<Lsn>,
     512              : 
     513              :     /// When the timeline was archived.
     514              :     ///
     515              :     /// Present for future flattening deliberations.
     516              :     pub archived_at: NaiveDateTime,
     517              : 
     518              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     519              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     520              :     pub delete_progress: TimelineDeleteProgress,
     521              : 
     522              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     523              :     pub deleted_from_ancestor: AtomicBool,
     524              : }
     525              : 
     526              : impl OffloadedTimeline {
     527              :     /// Obtains an offloaded timeline from a given timeline object.
     528              :     ///
     529              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     530              :     /// the timeline is not in a stopped state.
     531              :     /// Panics if the timeline is not archived.
     532           12 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     533           12 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     534           12 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     535           12 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     536           12 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     537           12 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     538           12 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     539           12 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     540              :             } else {
     541            0 :                 (None, None)
     542              :             };
     543           12 :         let archived_at = timeline
     544           12 :             .remote_client
     545           12 :             .archived_at_stopped_queue()?
     546           12 :             .expect("must be called on an archived timeline");
     547           12 :         Ok(Self {
     548           12 :             tenant_shard_id: timeline.tenant_shard_id,
     549           12 :             timeline_id: timeline.timeline_id,
     550           12 :             ancestor_timeline_id,
     551           12 :             ancestor_retain_lsn,
     552           12 :             archived_at,
     553           12 : 
     554           12 :             delete_progress: timeline.delete_progress.clone(),
     555           12 :             deleted_from_ancestor: AtomicBool::new(false),
     556           12 :         })
     557           12 :     }
     558            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     559            0 :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     560            0 :         // by the `initialize_gc_info` function.
     561            0 :         let OffloadedTimelineManifest {
     562            0 :             timeline_id,
     563            0 :             ancestor_timeline_id,
     564            0 :             ancestor_retain_lsn,
     565            0 :             archived_at,
     566            0 :         } = *manifest;
     567            0 :         Self {
     568            0 :             tenant_shard_id,
     569            0 :             timeline_id,
     570            0 :             ancestor_timeline_id,
     571            0 :             ancestor_retain_lsn,
     572            0 :             archived_at,
     573            0 :             delete_progress: TimelineDeleteProgress::default(),
     574            0 :             deleted_from_ancestor: AtomicBool::new(false),
     575            0 :         }
     576            0 :     }
     577           12 :     fn manifest(&self) -> OffloadedTimelineManifest {
     578           12 :         let Self {
     579           12 :             timeline_id,
     580           12 :             ancestor_timeline_id,
     581           12 :             ancestor_retain_lsn,
     582           12 :             archived_at,
     583           12 :             ..
     584           12 :         } = self;
     585           12 :         OffloadedTimelineManifest {
     586           12 :             timeline_id: *timeline_id,
     587           12 :             ancestor_timeline_id: *ancestor_timeline_id,
     588           12 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     589           12 :             archived_at: *archived_at,
     590           12 :         }
     591           12 :     }
     592              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     593            0 :     fn delete_from_ancestor_with_timelines(
     594            0 :         &self,
     595            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     596            0 :     ) {
     597            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     598            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     599              :         {
     600            0 :             if let Some((_, ancestor_timeline)) = timelines
     601            0 :                 .iter()
     602            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     603              :             {
     604            0 :                 let removal_happened = ancestor_timeline
     605            0 :                     .gc_info
     606            0 :                     .write()
     607            0 :                     .unwrap()
     608            0 :                     .remove_child_offloaded(self.timeline_id);
     609            0 :                 if !removal_happened {
     610            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     611            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     612            0 :                 }
     613            0 :             }
     614            0 :         }
     615            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     616            0 :     }
     617              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     618              :     ///
     619              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     620           12 :     fn defuse_for_tenant_drop(&self) {
     621           12 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     622           12 :     }
     623              : }
     624              : 
     625              : impl fmt::Debug for OffloadedTimeline {
     626            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     627            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     628            0 :     }
     629              : }
     630              : 
     631              : impl Drop for OffloadedTimeline {
     632           12 :     fn drop(&mut self) {
     633           12 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     634            0 :             tracing::warn!(
     635            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     636              :                 self.timeline_id
     637              :             );
     638           12 :         }
     639           12 :     }
     640              : }
     641              : 
     642              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     643              : pub enum MaybeOffloaded {
     644              :     Yes,
     645              :     No,
     646              : }
     647              : 
     648              : #[derive(Clone, Debug)]
     649              : pub enum TimelineOrOffloaded {
     650              :     Timeline(Arc<Timeline>),
     651              :     Offloaded(Arc<OffloadedTimeline>),
     652              : }
     653              : 
     654              : impl TimelineOrOffloaded {
     655            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     656            0 :         match self {
     657            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     658            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     659              :             }
     660            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     661            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     662              :             }
     663              :         }
     664            0 :     }
     665            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     666            0 :         self.arc_ref().tenant_shard_id()
     667            0 :     }
     668            0 :     pub fn timeline_id(&self) -> TimelineId {
     669            0 :         self.arc_ref().timeline_id()
     670            0 :     }
     671           12 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     672           12 :         match self {
     673           12 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     674            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     675              :         }
     676           12 :     }
     677            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     678            0 :         match self {
     679            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     680            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     681              :         }
     682            0 :     }
     683              : }
     684              : 
     685              : pub enum TimelineOrOffloadedArcRef<'a> {
     686              :     Timeline(&'a Arc<Timeline>),
     687              :     Offloaded(&'a Arc<OffloadedTimeline>),
     688              : }
     689              : 
     690              : impl TimelineOrOffloadedArcRef<'_> {
     691            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     692            0 :         match self {
     693            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     694            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     695              :         }
     696            0 :     }
     697            0 :     pub fn timeline_id(&self) -> TimelineId {
     698            0 :         match self {
     699            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     700            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     701              :         }
     702            0 :     }
     703              : }
     704              : 
     705              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     706            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     707            0 :         Self::Timeline(timeline)
     708            0 :     }
     709              : }
     710              : 
     711              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     712            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     713            0 :         Self::Offloaded(timeline)
     714            0 :     }
     715              : }
     716              : 
     717              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     718              : pub enum GetTimelineError {
     719              :     #[error("Timeline is shutting down")]
     720              :     ShuttingDown,
     721              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     722              :     NotActive {
     723              :         tenant_id: TenantShardId,
     724              :         timeline_id: TimelineId,
     725              :         state: TimelineState,
     726              :     },
     727              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     728              :     NotFound {
     729              :         tenant_id: TenantShardId,
     730              :         timeline_id: TimelineId,
     731              :     },
     732              : }
     733              : 
     734              : #[derive(Debug, thiserror::Error)]
     735              : pub enum LoadLocalTimelineError {
     736              :     #[error("FailedToLoad")]
     737              :     Load(#[source] anyhow::Error),
     738              :     #[error("FailedToResumeDeletion")]
     739              :     ResumeDeletion(#[source] anyhow::Error),
     740              : }
     741              : 
     742              : #[derive(thiserror::Error)]
     743              : pub enum DeleteTimelineError {
     744              :     #[error("NotFound")]
     745              :     NotFound,
     746              : 
     747              :     #[error("HasChildren")]
     748              :     HasChildren(Vec<TimelineId>),
     749              : 
     750              :     #[error("Timeline deletion is already in progress")]
     751              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     752              : 
     753              :     #[error("Cancelled")]
     754              :     Cancelled,
     755              : 
     756              :     #[error(transparent)]
     757              :     Other(#[from] anyhow::Error),
     758              : }
     759              : 
     760              : impl Debug for DeleteTimelineError {
     761            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     762            0 :         match self {
     763            0 :             Self::NotFound => write!(f, "NotFound"),
     764            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     765            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     766            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     767            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     768              :         }
     769            0 :     }
     770              : }
     771              : 
     772              : #[derive(thiserror::Error)]
     773              : pub enum TimelineArchivalError {
     774              :     #[error("NotFound")]
     775              :     NotFound,
     776              : 
     777              :     #[error("Timeout")]
     778              :     Timeout,
     779              : 
     780              :     #[error("Cancelled")]
     781              :     Cancelled,
     782              : 
     783              :     #[error("ancestor is archived: {}", .0)]
     784              :     HasArchivedParent(TimelineId),
     785              : 
     786              :     #[error("HasUnarchivedChildren")]
     787              :     HasUnarchivedChildren(Vec<TimelineId>),
     788              : 
     789              :     #[error("Timeline archival is already in progress")]
     790              :     AlreadyInProgress,
     791              : 
     792              :     #[error(transparent)]
     793              :     Other(anyhow::Error),
     794              : }
     795              : 
     796              : #[derive(thiserror::Error, Debug)]
     797              : pub(crate) enum TenantManifestError {
     798              :     #[error("Remote storage error: {0}")]
     799              :     RemoteStorage(anyhow::Error),
     800              : 
     801              :     #[error("Cancelled")]
     802              :     Cancelled,
     803              : }
     804              : 
     805              : impl From<TenantManifestError> for TimelineArchivalError {
     806            0 :     fn from(e: TenantManifestError) -> Self {
     807            0 :         match e {
     808            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     809            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     810              :         }
     811            0 :     }
     812              : }
     813              : 
     814              : impl Debug for TimelineArchivalError {
     815            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     816            0 :         match self {
     817            0 :             Self::NotFound => write!(f, "NotFound"),
     818            0 :             Self::Timeout => write!(f, "Timeout"),
     819            0 :             Self::Cancelled => write!(f, "Cancelled"),
     820            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     821            0 :             Self::HasUnarchivedChildren(c) => {
     822            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     823              :             }
     824            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     825            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     826              :         }
     827            0 :     }
     828              : }
     829              : 
     830              : pub enum SetStoppingError {
     831              :     AlreadyStopping(completion::Barrier),
     832              :     Broken,
     833              : }
     834              : 
     835              : impl Debug for SetStoppingError {
     836            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     837            0 :         match self {
     838            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     839            0 :             Self::Broken => write!(f, "Broken"),
     840              :         }
     841            0 :     }
     842              : }
     843              : 
     844              : /// Arguments to [`TenantShard::create_timeline`].
     845              : ///
     846              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     847              : /// is `None`, the result of the timeline create call is not deterministic.
     848              : ///
     849              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     850              : #[derive(Debug)]
     851              : pub(crate) enum CreateTimelineParams {
     852              :     Bootstrap(CreateTimelineParamsBootstrap),
     853              :     Branch(CreateTimelineParamsBranch),
     854              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     855              : }
     856              : 
     857              : #[derive(Debug)]
     858              : pub(crate) struct CreateTimelineParamsBootstrap {
     859              :     pub(crate) new_timeline_id: TimelineId,
     860              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     861              :     pub(crate) pg_version: u32,
     862              : }
     863              : 
     864              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     865              : #[derive(Debug)]
     866              : pub(crate) struct CreateTimelineParamsBranch {
     867              :     pub(crate) new_timeline_id: TimelineId,
     868              :     pub(crate) ancestor_timeline_id: TimelineId,
     869              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     870              : }
     871              : 
     872              : #[derive(Debug)]
     873              : pub(crate) struct CreateTimelineParamsImportPgdata {
     874              :     pub(crate) new_timeline_id: TimelineId,
     875              :     pub(crate) location: import_pgdata::index_part_format::Location,
     876              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     877              : }
     878              : 
     879              : /// What is used to determine idempotency of a [`TenantShard::create_timeline`] call in  [`TenantShard::start_creating_timeline`] in  [`TenantShard::start_creating_timeline`].
     880              : ///
     881              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     882              : ///
     883              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     884              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     885              : ///
     886              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     887              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     888              : ///
     889              : /// Notes:
     890              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     891              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     892              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     893              : ///
     894              : #[derive(Debug, Clone, PartialEq, Eq)]
     895              : pub(crate) enum CreateTimelineIdempotency {
     896              :     /// NB: special treatment, see comment in [`Self`].
     897              :     FailWithConflict,
     898              :     Bootstrap {
     899              :         pg_version: u32,
     900              :     },
     901              :     /// NB: branches always have the same `pg_version` as their ancestor.
     902              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     903              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     904              :     /// determining the child branch pg_version.
     905              :     Branch {
     906              :         ancestor_timeline_id: TimelineId,
     907              :         ancestor_start_lsn: Lsn,
     908              :     },
     909              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     910              : }
     911              : 
     912              : #[derive(Debug, Clone, PartialEq, Eq)]
     913              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     914              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     915              : }
     916              : 
     917              : /// What is returned by [`TenantShard::start_creating_timeline`].
     918              : #[must_use]
     919              : enum StartCreatingTimelineResult {
     920              :     CreateGuard(TimelineCreateGuard),
     921              :     Idempotent(Arc<Timeline>),
     922              : }
     923              : 
     924              : #[allow(clippy::large_enum_variant, reason = "TODO")]
     925              : enum TimelineInitAndSyncResult {
     926              :     ReadyToActivate(Arc<Timeline>),
     927              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
     928              : }
     929              : 
     930              : impl TimelineInitAndSyncResult {
     931            0 :     fn ready_to_activate(self) -> Option<Arc<Timeline>> {
     932            0 :         match self {
     933            0 :             Self::ReadyToActivate(timeline) => Some(timeline),
     934            0 :             _ => None,
     935              :         }
     936            0 :     }
     937              : }
     938              : 
     939              : #[must_use]
     940              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
     941              :     timeline: Arc<Timeline>,
     942              :     import_pgdata: import_pgdata::index_part_format::Root,
     943              :     guard: TimelineCreateGuard,
     944              : }
     945              : 
     946              : /// What is returned by [`TenantShard::create_timeline`].
     947              : enum CreateTimelineResult {
     948              :     Created(Arc<Timeline>),
     949              :     Idempotent(Arc<Timeline>),
     950              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`TenantShard::timelines`] when
     951              :     /// we return this result, nor will this concrete object ever be added there.
     952              :     /// Cf method comment on [`TenantShard::create_timeline_import_pgdata`].
     953              :     ImportSpawned(Arc<Timeline>),
     954              : }
     955              : 
     956              : impl CreateTimelineResult {
     957            0 :     fn discriminant(&self) -> &'static str {
     958            0 :         match self {
     959            0 :             Self::Created(_) => "Created",
     960            0 :             Self::Idempotent(_) => "Idempotent",
     961            0 :             Self::ImportSpawned(_) => "ImportSpawned",
     962              :         }
     963            0 :     }
     964            0 :     fn timeline(&self) -> &Arc<Timeline> {
     965            0 :         match self {
     966            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     967            0 :         }
     968            0 :     }
     969              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
     970              :     #[cfg(test)]
     971         1416 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
     972         1416 :         match self {
     973         1416 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
     974         1416 :         }
     975         1416 :     }
     976              : }
     977              : 
     978              : #[derive(thiserror::Error, Debug)]
     979              : pub enum CreateTimelineError {
     980              :     #[error("creation of timeline with the given ID is in progress")]
     981              :     AlreadyCreating,
     982              :     #[error("timeline already exists with different parameters")]
     983              :     Conflict,
     984              :     #[error(transparent)]
     985              :     AncestorLsn(anyhow::Error),
     986              :     #[error("ancestor timeline is not active")]
     987              :     AncestorNotActive,
     988              :     #[error("ancestor timeline is archived")]
     989              :     AncestorArchived,
     990              :     #[error("tenant shutting down")]
     991              :     ShuttingDown,
     992              :     #[error(transparent)]
     993              :     Other(#[from] anyhow::Error),
     994              : }
     995              : 
     996              : #[derive(thiserror::Error, Debug)]
     997              : pub enum InitdbError {
     998              :     #[error("Operation was cancelled")]
     999              :     Cancelled,
    1000              :     #[error(transparent)]
    1001              :     Other(anyhow::Error),
    1002              :     #[error(transparent)]
    1003              :     Inner(postgres_initdb::Error),
    1004              : }
    1005              : 
    1006              : enum CreateTimelineCause {
    1007              :     Load,
    1008              :     Delete,
    1009              : }
    1010              : 
    1011              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1012              : enum LoadTimelineCause {
    1013              :     Attach,
    1014              :     Unoffload,
    1015              :     ImportPgdata {
    1016              :         create_guard: TimelineCreateGuard,
    1017              :         activate: ActivateTimelineArgs,
    1018              :     },
    1019              : }
    1020              : 
    1021              : #[derive(thiserror::Error, Debug)]
    1022              : pub(crate) enum GcError {
    1023              :     // The tenant is shutting down
    1024              :     #[error("tenant shutting down")]
    1025              :     TenantCancelled,
    1026              : 
    1027              :     // The tenant is shutting down
    1028              :     #[error("timeline shutting down")]
    1029              :     TimelineCancelled,
    1030              : 
    1031              :     // The tenant is in a state inelegible to run GC
    1032              :     #[error("not active")]
    1033              :     NotActive,
    1034              : 
    1035              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1036              :     #[error("not active")]
    1037              :     BadLsn { why: String },
    1038              : 
    1039              :     // A remote storage error while scheduling updates after compaction
    1040              :     #[error(transparent)]
    1041              :     Remote(anyhow::Error),
    1042              : 
    1043              :     // An error reading while calculating GC cutoffs
    1044              :     #[error(transparent)]
    1045              :     GcCutoffs(PageReconstructError),
    1046              : 
    1047              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1048              :     #[error("timeline not found")]
    1049              :     TimelineNotFound,
    1050              : }
    1051              : 
    1052              : impl From<PageReconstructError> for GcError {
    1053            0 :     fn from(value: PageReconstructError) -> Self {
    1054            0 :         match value {
    1055            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1056            0 :             other => Self::GcCutoffs(other),
    1057              :         }
    1058            0 :     }
    1059              : }
    1060              : 
    1061              : impl From<NotInitialized> for GcError {
    1062            0 :     fn from(value: NotInitialized) -> Self {
    1063            0 :         match value {
    1064            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1065            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1066              :         }
    1067            0 :     }
    1068              : }
    1069              : 
    1070              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1071            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1072            0 :         GcError::TimelineCancelled
    1073            0 :     }
    1074              : }
    1075              : 
    1076              : #[derive(thiserror::Error, Debug)]
    1077              : pub(crate) enum LoadConfigError {
    1078              :     #[error("TOML deserialization error: '{0}'")]
    1079              :     DeserializeToml(#[from] toml_edit::de::Error),
    1080              : 
    1081              :     #[error("Config not found at {0}")]
    1082              :     NotFound(Utf8PathBuf),
    1083              : }
    1084              : 
    1085              : impl TenantShard {
    1086              :     /// Yet another helper for timeline initialization.
    1087              :     ///
    1088              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1089              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1090              :     /// - Downloads remote index file and adds remote files to the layer map
    1091              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1092              :     ///
    1093              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1094              :     /// it is marked as Active.
    1095              :     #[allow(clippy::too_many_arguments)]
    1096           36 :     async fn timeline_init_and_sync(
    1097           36 :         self: &Arc<Self>,
    1098           36 :         timeline_id: TimelineId,
    1099           36 :         resources: TimelineResources,
    1100           36 :         mut index_part: IndexPart,
    1101           36 :         metadata: TimelineMetadata,
    1102           36 :         previous_heatmap: Option<PreviousHeatmap>,
    1103           36 :         ancestor: Option<Arc<Timeline>>,
    1104           36 :         cause: LoadTimelineCause,
    1105           36 :         ctx: &RequestContext,
    1106           36 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1107           36 :         let tenant_id = self.tenant_shard_id;
    1108           36 : 
    1109           36 :         let import_pgdata = index_part.import_pgdata.take();
    1110           36 :         let idempotency = match &import_pgdata {
    1111            0 :             Some(import_pgdata) => {
    1112            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1113            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1114            0 :                 })
    1115              :             }
    1116              :             None => {
    1117           36 :                 if metadata.ancestor_timeline().is_none() {
    1118           24 :                     CreateTimelineIdempotency::Bootstrap {
    1119           24 :                         pg_version: metadata.pg_version(),
    1120           24 :                     }
    1121              :                 } else {
    1122           12 :                     CreateTimelineIdempotency::Branch {
    1123           12 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1124           12 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1125           12 :                     }
    1126              :                 }
    1127              :             }
    1128              :         };
    1129              : 
    1130           36 :         let (timeline, timeline_ctx) = self.create_timeline_struct(
    1131           36 :             timeline_id,
    1132           36 :             &metadata,
    1133           36 :             previous_heatmap,
    1134           36 :             ancestor.clone(),
    1135           36 :             resources,
    1136           36 :             CreateTimelineCause::Load,
    1137           36 :             idempotency.clone(),
    1138           36 :             index_part.gc_compaction.clone(),
    1139           36 :             index_part.rel_size_migration.clone(),
    1140           36 :             ctx,
    1141           36 :         )?;
    1142           36 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1143           36 :         anyhow::ensure!(
    1144           36 :             disk_consistent_lsn.is_valid(),
    1145            0 :             "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
    1146              :         );
    1147           36 :         assert_eq!(
    1148           36 :             disk_consistent_lsn,
    1149           36 :             metadata.disk_consistent_lsn(),
    1150            0 :             "these are used interchangeably"
    1151              :         );
    1152              : 
    1153           36 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1154              : 
    1155           36 :         timeline
    1156           36 :             .load_layer_map(disk_consistent_lsn, index_part)
    1157           36 :             .await
    1158           36 :             .with_context(|| {
    1159            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1160           36 :             })?;
    1161              : 
    1162              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1163              :         // to the archival operation. To allow warming this timeline up, generate
    1164              :         // a previous heatmap which contains all visible layers in the layer map.
    1165              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1166              :         // for the timeline.
    1167           36 :         if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
    1168            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1169            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1170            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1171              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1172              :                 // If the current branch point greater than the previous one use the the heatmap
    1173              :                 // we just generated - it should include more layers.
    1174            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1175            0 :                     tline
    1176            0 :                         .previous_heatmap
    1177            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1178            0 :                 } else {
    1179            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1180              :                 }
    1181              : 
    1182            0 :                 match tline.ancestor_timeline() {
    1183            0 :                     Some(ancestor) => {
    1184            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1185              :                             // Ancestor timeline is shutting down.
    1186            0 :                             break;
    1187            0 :                         }
    1188            0 : 
    1189            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1190              :                     }
    1191            0 :                     None => {
    1192            0 :                         tline_ending_at = None;
    1193            0 :                     }
    1194              :                 }
    1195              :             }
    1196           36 :         }
    1197              : 
    1198            0 :         match import_pgdata {
    1199            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1200            0 :                 match cause {
    1201            0 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1202              :                     LoadTimelineCause::ImportPgdata { .. } => {
    1203            0 :                         unreachable!(
    1204            0 :                             "ImportPgdata should not be reloading timeline import is done and persisted as such in s3"
    1205            0 :                         )
    1206              :                     }
    1207              :                 }
    1208            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1209            0 :                 if !guard.insert(timeline_id) {
    1210              :                     // We should never try and load the same timeline twice during startup
    1211            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1212            0 :                 }
    1213            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1214            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1215            0 :                     owning_tenant: self.clone(),
    1216            0 :                     timeline_id,
    1217            0 :                     idempotency,
    1218            0 :                     // The users of this specific return value don't need the timline_path in there.
    1219            0 :                     timeline_path: timeline
    1220            0 :                         .conf
    1221            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1222            0 :                 };
    1223            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1224            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1225            0 :                         timeline,
    1226            0 :                         import_pgdata,
    1227            0 :                         guard: timeline_create_guard,
    1228            0 :                     },
    1229            0 :                 ))
    1230              :             }
    1231              :             Some(_) | None => {
    1232              :                 {
    1233           36 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1234           36 :                     match timelines_accessor.entry(timeline_id) {
    1235              :                         // We should never try and load the same timeline twice during startup
    1236              :                         Entry::Occupied(_) => {
    1237            0 :                             unreachable!(
    1238            0 :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1239            0 :                             );
    1240              :                         }
    1241           36 :                         Entry::Vacant(v) => {
    1242           36 :                             v.insert(Arc::clone(&timeline));
    1243           36 :                             timeline.maybe_spawn_flush_loop();
    1244           36 :                         }
    1245              :                     }
    1246              :                 }
    1247              : 
    1248              :                 // Sanity check: a timeline should have some content.
    1249           36 :                 anyhow::ensure!(
    1250           36 :                     ancestor.is_some()
    1251           24 :                         || timeline
    1252           24 :                             .layers
    1253           24 :                             .read()
    1254           24 :                             .await
    1255           24 :                             .layer_map()
    1256           24 :                             .expect("currently loading, layer manager cannot be shutdown already")
    1257           24 :                             .iter_historic_layers()
    1258           24 :                             .next()
    1259           24 :                             .is_some(),
    1260            0 :                     "Timeline has no ancestor and no layer files"
    1261              :                 );
    1262              : 
    1263           36 :                 match cause {
    1264           36 :                     LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
    1265              :                     LoadTimelineCause::ImportPgdata {
    1266            0 :                         create_guard,
    1267            0 :                         activate,
    1268            0 :                     } => {
    1269            0 :                         // TODO: see the comment in the task code above how I'm not so certain
    1270            0 :                         // it is safe to activate here because of concurrent shutdowns.
    1271            0 :                         match activate {
    1272            0 :                             ActivateTimelineArgs::Yes { broker_client } => {
    1273            0 :                                 info!("activating timeline after reload from pgdata import task");
    1274            0 :                                 timeline.activate(self.clone(), broker_client, None, &timeline_ctx);
    1275              :                             }
    1276            0 :                             ActivateTimelineArgs::No => (),
    1277              :                         }
    1278            0 :                         drop(create_guard);
    1279              :                     }
    1280              :                 }
    1281              : 
    1282           36 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
    1283              :             }
    1284              :         }
    1285           36 :     }
    1286              : 
    1287              :     /// Attach a tenant that's available in cloud storage.
    1288              :     ///
    1289              :     /// This returns quickly, after just creating the in-memory object
    1290              :     /// Tenant struct and launching a background task to download
    1291              :     /// the remote index files.  On return, the tenant is most likely still in
    1292              :     /// Attaching state, and it will become Active once the background task
    1293              :     /// finishes. You can use wait_until_active() to wait for the task to
    1294              :     /// complete.
    1295              :     ///
    1296              :     #[allow(clippy::too_many_arguments)]
    1297            0 :     pub(crate) fn spawn(
    1298            0 :         conf: &'static PageServerConf,
    1299            0 :         tenant_shard_id: TenantShardId,
    1300            0 :         resources: TenantSharedResources,
    1301            0 :         attached_conf: AttachedTenantConf,
    1302            0 :         shard_identity: ShardIdentity,
    1303            0 :         init_order: Option<InitializationOrder>,
    1304            0 :         mode: SpawnMode,
    1305            0 :         ctx: &RequestContext,
    1306            0 :     ) -> Result<Arc<TenantShard>, GlobalShutDown> {
    1307            0 :         let wal_redo_manager =
    1308            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1309              : 
    1310              :         let TenantSharedResources {
    1311            0 :             broker_client,
    1312            0 :             remote_storage,
    1313            0 :             deletion_queue_client,
    1314            0 :             l0_flush_global_state,
    1315            0 :         } = resources;
    1316            0 : 
    1317            0 :         let attach_mode = attached_conf.location.attach_mode;
    1318            0 :         let generation = attached_conf.location.generation;
    1319            0 : 
    1320            0 :         let tenant = Arc::new(TenantShard::new(
    1321            0 :             TenantState::Attaching,
    1322            0 :             conf,
    1323            0 :             attached_conf,
    1324            0 :             shard_identity,
    1325            0 :             Some(wal_redo_manager),
    1326            0 :             tenant_shard_id,
    1327            0 :             remote_storage.clone(),
    1328            0 :             deletion_queue_client,
    1329            0 :             l0_flush_global_state,
    1330            0 :         ));
    1331            0 : 
    1332            0 :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1333            0 :         // we shut down while attaching.
    1334            0 :         let attach_gate_guard = tenant
    1335            0 :             .gate
    1336            0 :             .enter()
    1337            0 :             .expect("We just created the TenantShard: nothing else can have shut it down yet");
    1338            0 : 
    1339            0 :         // Do all the hard work in the background
    1340            0 :         let tenant_clone = Arc::clone(&tenant);
    1341            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1342            0 :         task_mgr::spawn(
    1343            0 :             &tokio::runtime::Handle::current(),
    1344            0 :             TaskKind::Attach,
    1345            0 :             tenant_shard_id,
    1346            0 :             None,
    1347            0 :             "attach tenant",
    1348            0 :             async move {
    1349            0 : 
    1350            0 :                 info!(
    1351              :                     ?attach_mode,
    1352            0 :                     "Attaching tenant"
    1353              :                 );
    1354              : 
    1355            0 :                 let _gate_guard = attach_gate_guard;
    1356            0 : 
    1357            0 :                 // Is this tenant being spawned as part of process startup?
    1358            0 :                 let starting_up = init_order.is_some();
    1359            0 :                 scopeguard::defer! {
    1360            0 :                     if starting_up {
    1361            0 :                         TENANT.startup_complete.inc();
    1362            0 :                     }
    1363            0 :                 }
    1364              : 
    1365            0 :                 fn make_broken_or_stopping(t: &TenantShard, err: anyhow::Error) {
    1366            0 :                     t.state.send_modify(|state| match state {
    1367              :                         // TODO: the old code alluded to DeleteTenantFlow sometimes setting
    1368              :                         // TenantState::Stopping before we get here, but this may be outdated.
    1369              :                         // Let's find out with a testing assertion. If this doesn't fire, and the
    1370              :                         // logs don't show this happening in production, remove the Stopping cases.
    1371            0 :                         TenantState::Stopping{..} if cfg!(any(test, feature = "testing")) => {
    1372            0 :                             panic!("unexpected TenantState::Stopping during attach")
    1373              :                         }
    1374              :                         // If the tenant is cancelled, assume the error was caused by cancellation.
    1375            0 :                         TenantState::Attaching if t.cancel.is_cancelled() => {
    1376            0 :                             info!("attach cancelled, setting tenant state to Stopping: {err}");
    1377              :                             // NB: progress None tells `set_stopping` that attach has cancelled.
    1378            0 :                             *state = TenantState::Stopping { progress: None };
    1379              :                         }
    1380              :                         // According to the old code, DeleteTenantFlow may already have set this to
    1381              :                         // Stopping. Retain its progress.
    1382              :                         // TODO: there is no DeleteTenantFlow. Is this still needed? See above.
    1383            0 :                         TenantState::Stopping { progress } if t.cancel.is_cancelled() => {
    1384            0 :                             assert!(progress.is_some(), "concurrent attach cancellation");
    1385            0 :                             info!("attach cancelled, already Stopping: {err}");
    1386              :                         }
    1387              :                         // Mark the tenant as broken.
    1388              :                         TenantState::Attaching | TenantState::Stopping { .. } => {
    1389            0 :                             error!("attach failed, setting tenant state to Broken (was {state}): {err:?}");
    1390            0 :                             *state = TenantState::broken_from_reason(err.to_string())
    1391              :                         }
    1392              :                         // The attach task owns the tenant state until activated.
    1393            0 :                         state => panic!("invalid tenant state {state} during attach: {err:?}"),
    1394            0 :                     });
    1395            0 :                 }
    1396              : 
    1397              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1398            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1399            0 :                     make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1400            0 :                     return Ok(());
    1401            0 :                 }
    1402            0 : 
    1403            0 :                 let mut init_order = init_order;
    1404            0 :                 // take the completion because initial tenant loading will complete when all of
    1405            0 :                 // these tasks complete.
    1406            0 :                 let _completion = init_order
    1407            0 :                     .as_mut()
    1408            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1409            0 :                 let remote_load_completion = init_order
    1410            0 :                     .as_mut()
    1411            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1412              : 
    1413              :                 enum AttachType<'a> {
    1414              :                     /// We are attaching this tenant lazily in the background.
    1415              :                     Warmup {
    1416              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1417              :                         during_startup: bool
    1418              :                     },
    1419              :                     /// We are attaching this tenant as soon as we can, because for example an
    1420              :                     /// endpoint tried to access it.
    1421              :                     OnDemand,
    1422              :                     /// During normal operations after startup, we are attaching a tenant, and
    1423              :                     /// eager attach was requested.
    1424              :                     Normal,
    1425              :                 }
    1426              : 
    1427            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1428              :                     // Before doing any I/O, wait for at least one of:
    1429              :                     // - A client attempting to access to this tenant (on-demand loading)
    1430              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1431              : 
    1432            0 :                     tokio::select!(
    1433            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1434            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1435            0 :                             tracing::info!("Activating tenant (on-demand)");
    1436            0 :                             AttachType::OnDemand
    1437              :                         },
    1438            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1439            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1440            0 :                             tracing::info!("Activating tenant (warmup)");
    1441            0 :                             AttachType::Warmup {
    1442            0 :                                 _permit,
    1443            0 :                                 during_startup: init_order.is_some()
    1444            0 :                             }
    1445              :                         }
    1446            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1447              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1448              :                             // stayed in Activating for such a long time that shutdown found it in
    1449              :                             // that state.
    1450            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1451              :                             // Set the tenant to Stopping to signal `set_stopping` that we're done.
    1452            0 :                             make_broken_or_stopping(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"));
    1453            0 :                             return Ok(());
    1454              :                         },
    1455              :                     )
    1456              :                 } else {
    1457              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1458              :                     // concurrent_tenant_warmup queue
    1459            0 :                     AttachType::Normal
    1460              :                 };
    1461              : 
    1462            0 :                 let preload = match &mode {
    1463              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1464            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1465            0 :                         let res = tenant_clone
    1466            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1467            0 :                             .await;
    1468            0 :                         match res {
    1469            0 :                             Ok(p) => Some(p),
    1470            0 :                             Err(e) => {
    1471            0 :                                 make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1472            0 :                                 return Ok(());
    1473              :                             }
    1474              :                         }
    1475              :                     }
    1476              : 
    1477              :                 };
    1478              : 
    1479              :                 // Remote preload is complete.
    1480            0 :                 drop(remote_load_completion);
    1481            0 : 
    1482            0 : 
    1483            0 :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1484            0 :                 let attach_start = std::time::Instant::now();
    1485            0 :                 let attached = {
    1486            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1487            0 :                     tenant_clone.attach(preload, &ctx).await
    1488              :                 };
    1489            0 :                 let attach_duration = attach_start.elapsed();
    1490            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1491            0 : 
    1492            0 :                 match attached {
    1493              :                     Ok(()) => {
    1494            0 :                         info!("attach finished, activating");
    1495            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1496              :                     }
    1497            0 :                     Err(e) => make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e)),
    1498              :                 }
    1499              : 
    1500              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1501              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1502              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1503              :                 //
    1504              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1505              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1506              :                 // then warmup will wait for that before proceeding to the next tenant.
    1507            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1508            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1509            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1510            0 :                     while futs.next().await.is_some() {}
    1511            0 :                     tracing::info!("Warm-up complete");
    1512            0 :                 }
    1513              : 
    1514            0 :                 Ok(())
    1515            0 :             }
    1516            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1517              :         );
    1518            0 :         Ok(tenant)
    1519            0 :     }
    1520              : 
    1521              :     #[instrument(skip_all)]
    1522              :     pub(crate) async fn preload(
    1523              :         self: &Arc<Self>,
    1524              :         remote_storage: &GenericRemoteStorage,
    1525              :         cancel: CancellationToken,
    1526              :     ) -> anyhow::Result<TenantPreload> {
    1527              :         span::debug_assert_current_span_has_tenant_id();
    1528              :         // Get list of remote timelines
    1529              :         // download index files for every tenant timeline
    1530              :         info!("listing remote timelines");
    1531              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1532              :             remote_storage,
    1533              :             self.tenant_shard_id,
    1534              :             cancel.clone(),
    1535              :         )
    1536              :         .await?;
    1537              : 
    1538              :         let tenant_manifest = match download_tenant_manifest(
    1539              :             remote_storage,
    1540              :             &self.tenant_shard_id,
    1541              :             self.generation,
    1542              :             &cancel,
    1543              :         )
    1544              :         .await
    1545              :         {
    1546              :             Ok((tenant_manifest, _, _)) => Some(tenant_manifest),
    1547              :             Err(DownloadError::NotFound) => None,
    1548              :             Err(err) => return Err(err.into()),
    1549              :         };
    1550              : 
    1551              :         info!(
    1552              :             "found {} timelines ({} offloaded timelines)",
    1553              :             remote_timeline_ids.len(),
    1554              :             tenant_manifest
    1555              :                 .as_ref()
    1556           36 :                 .map(|m| m.offloaded_timelines.len())
    1557              :                 .unwrap_or(0)
    1558              :         );
    1559              : 
    1560              :         for k in other_keys {
    1561              :             warn!("Unexpected non timeline key {k}");
    1562              :         }
    1563              : 
    1564              :         // Avoid downloading IndexPart of offloaded timelines.
    1565              :         let mut offloaded_with_prefix = HashSet::new();
    1566              :         if let Some(tenant_manifest) = &tenant_manifest {
    1567              :             for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1568              :                 if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1569              :                     offloaded_with_prefix.insert(offloaded.timeline_id);
    1570              :                 } else {
    1571              :                     // We'll take care later of timelines in the manifest without a prefix
    1572              :                 }
    1573              :             }
    1574              :         }
    1575              : 
    1576              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1577              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1578              :         // will kick the secondary in any case and cause a download.
    1579              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1580              : 
    1581              :         let timelines = self
    1582              :             .load_timelines_metadata(
    1583              :                 remote_timeline_ids,
    1584              :                 remote_storage,
    1585              :                 maybe_heatmap_at,
    1586              :                 cancel,
    1587              :             )
    1588              :             .await?;
    1589              : 
    1590              :         Ok(TenantPreload {
    1591              :             tenant_manifest,
    1592              :             timelines: timelines
    1593              :                 .into_iter()
    1594           36 :                 .map(|(id, tl)| (id, Some(tl)))
    1595            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1596              :                 .collect(),
    1597              :         })
    1598              :     }
    1599              : 
    1600         1404 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1601         1404 :         if !self.conf.load_previous_heatmap {
    1602            0 :             return None;
    1603         1404 :         }
    1604         1404 : 
    1605         1404 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1606         1404 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1607            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1608            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1609            0 :                 Err(err) => {
    1610            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1611            0 :                     None
    1612              :                 }
    1613              :             },
    1614         1404 :             Err(err) => match err.kind() {
    1615         1404 :                 std::io::ErrorKind::NotFound => None,
    1616              :                 _ => {
    1617            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1618            0 :                     None
    1619              :                 }
    1620              :             },
    1621              :         }
    1622         1404 :     }
    1623              : 
    1624              :     ///
    1625              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1626              :     ///
    1627              :     /// No background tasks are started as part of this routine.
    1628              :     ///
    1629         1404 :     async fn attach(
    1630         1404 :         self: &Arc<TenantShard>,
    1631         1404 :         preload: Option<TenantPreload>,
    1632         1404 :         ctx: &RequestContext,
    1633         1404 :     ) -> anyhow::Result<()> {
    1634         1404 :         span::debug_assert_current_span_has_tenant_id();
    1635         1404 : 
    1636         1404 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1637              : 
    1638         1404 :         let Some(preload) = preload else {
    1639            0 :             anyhow::bail!(
    1640            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1641            0 :             );
    1642              :         };
    1643              : 
    1644         1404 :         let mut offloaded_timeline_ids = HashSet::new();
    1645         1404 :         let mut offloaded_timelines_list = Vec::new();
    1646         1404 :         if let Some(tenant_manifest) = &preload.tenant_manifest {
    1647           36 :             for timeline_manifest in tenant_manifest.offloaded_timelines.iter() {
    1648            0 :                 let timeline_id = timeline_manifest.timeline_id;
    1649            0 :                 let offloaded_timeline =
    1650            0 :                     OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1651            0 :                 offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1652            0 :                 offloaded_timeline_ids.insert(timeline_id);
    1653            0 :             }
    1654         1368 :         }
    1655              :         // Complete deletions for offloaded timeline id's from manifest.
    1656              :         // The manifest will be uploaded later in this function.
    1657         1404 :         offloaded_timelines_list
    1658         1404 :             .retain(|(offloaded_id, offloaded)| {
    1659            0 :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1660            0 :                 // If there is dangling references in another location, they need to be cleaned up.
    1661            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1662            0 :                 if delete {
    1663            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1664            0 :                     offloaded.defuse_for_tenant_drop();
    1665            0 :                 }
    1666            0 :                 !delete
    1667         1404 :         });
    1668         1404 : 
    1669         1404 :         let mut timelines_to_resume_deletions = vec![];
    1670         1404 : 
    1671         1404 :         let mut remote_index_and_client = HashMap::new();
    1672         1404 :         let mut timeline_ancestors = HashMap::new();
    1673         1404 :         let mut existent_timelines = HashSet::new();
    1674         1440 :         for (timeline_id, preload) in preload.timelines {
    1675           36 :             let Some(preload) = preload else { continue };
    1676              :             // This is an invariant of the `preload` function's API
    1677           36 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1678           36 :             let index_part = match preload.index_part {
    1679           36 :                 Ok(i) => {
    1680           36 :                     debug!("remote index part exists for timeline {timeline_id}");
    1681              :                     // We found index_part on the remote, this is the standard case.
    1682           36 :                     existent_timelines.insert(timeline_id);
    1683           36 :                     i
    1684              :                 }
    1685              :                 Err(DownloadError::NotFound) => {
    1686              :                     // There is no index_part on the remote. We only get here
    1687              :                     // if there is some prefix for the timeline in the remote storage.
    1688              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1689              :                     // remnant from a prior incomplete creation or deletion attempt.
    1690              :                     // Delete the local directory as the deciding criterion for a
    1691              :                     // timeline's existence is presence of index_part.
    1692            0 :                     info!(%timeline_id, "index_part not found on remote");
    1693            0 :                     continue;
    1694              :                 }
    1695            0 :                 Err(DownloadError::Fatal(why)) => {
    1696            0 :                     // If, while loading one remote timeline, we saw an indication that our generation
    1697            0 :                     // number is likely invalid, then we should not load the whole tenant.
    1698            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1699            0 :                     anyhow::bail!(why.to_string());
    1700              :                 }
    1701            0 :                 Err(e) => {
    1702            0 :                     // Some (possibly ephemeral) error happened during index_part download.
    1703            0 :                     // Pretend the timeline exists to not delete the timeline directory,
    1704            0 :                     // as it might be a temporary issue and we don't want to re-download
    1705            0 :                     // everything after it resolves.
    1706            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1707              : 
    1708            0 :                     existent_timelines.insert(timeline_id);
    1709            0 :                     continue;
    1710              :                 }
    1711              :             };
    1712           36 :             match index_part {
    1713           36 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1714           36 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1715           36 :                     remote_index_and_client.insert(
    1716           36 :                         timeline_id,
    1717           36 :                         (index_part, preload.client, preload.previous_heatmap),
    1718           36 :                     );
    1719           36 :                 }
    1720            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1721            0 :                     info!(
    1722            0 :                         "timeline {} is deleted, picking to resume deletion",
    1723              :                         timeline_id
    1724              :                     );
    1725            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1726              :                 }
    1727              :             }
    1728              :         }
    1729              : 
    1730         1404 :         let mut gc_blocks = HashMap::new();
    1731              : 
    1732              :         // For every timeline, download the metadata file, scan the local directory,
    1733              :         // and build a layer map that contains an entry for each remote and local
    1734              :         // layer file.
    1735         1404 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1736         1440 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1737           36 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1738           36 :                 .remove(&timeline_id)
    1739           36 :                 .expect("just put it in above");
    1740              : 
    1741           36 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1742              :                 // could just filter these away, but it helps while testing
    1743            0 :                 anyhow::ensure!(
    1744            0 :                     !blocking.reasons.is_empty(),
    1745            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1746              :                 );
    1747            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1748            0 :                 assert!(prev.is_none());
    1749           36 :             }
    1750              : 
    1751              :             // TODO again handle early failure
    1752           36 :             let effect = self
    1753           36 :                 .load_remote_timeline(
    1754           36 :                     timeline_id,
    1755           36 :                     index_part,
    1756           36 :                     remote_metadata,
    1757           36 :                     previous_heatmap,
    1758           36 :                     self.get_timeline_resources_for(remote_client),
    1759           36 :                     LoadTimelineCause::Attach,
    1760           36 :                     ctx,
    1761           36 :                 )
    1762           36 :                 .await
    1763           36 :                 .with_context(|| {
    1764            0 :                     format!(
    1765            0 :                         "failed to load remote timeline {} for tenant {}",
    1766            0 :                         timeline_id, self.tenant_shard_id
    1767            0 :                     )
    1768           36 :                 })?;
    1769              : 
    1770           36 :             match effect {
    1771           36 :                 TimelineInitAndSyncResult::ReadyToActivate(_) => {
    1772           36 :                     // activation happens later, on Tenant::activate
    1773           36 :                 }
    1774              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1775              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1776            0 :                         timeline,
    1777            0 :                         import_pgdata,
    1778            0 :                         guard,
    1779            0 :                     },
    1780            0 :                 ) => {
    1781            0 :                     tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1782            0 :                         timeline,
    1783            0 :                         import_pgdata,
    1784            0 :                         ActivateTimelineArgs::No,
    1785            0 :                         guard,
    1786            0 :                         ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    1787            0 :                     ));
    1788            0 :                 }
    1789              :             }
    1790              :         }
    1791              : 
    1792              :         // Walk through deleted timelines, resume deletion
    1793         1404 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1794            0 :             remote_timeline_client
    1795            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1796            0 :                 .context("init queue stopped")
    1797            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1798              : 
    1799            0 :             DeleteTimelineFlow::resume_deletion(
    1800            0 :                 Arc::clone(self),
    1801            0 :                 timeline_id,
    1802            0 :                 &index_part.metadata,
    1803            0 :                 remote_timeline_client,
    1804            0 :                 ctx,
    1805            0 :             )
    1806            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1807            0 :             .await
    1808            0 :             .context("resume_deletion")
    1809            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1810              :         }
    1811         1404 :         {
    1812         1404 :             let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
    1813         1404 :             offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
    1814         1404 :         }
    1815              : 
    1816              :         // Stash the preloaded tenant manifest, and upload a new manifest if changed.
    1817              :         //
    1818              :         // NB: this must happen after the tenant is fully populated above. In particular the
    1819              :         // offloaded timelines, which are included in the manifest.
    1820              :         {
    1821         1404 :             let mut guard = self.remote_tenant_manifest.lock().await;
    1822         1404 :             assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
    1823         1404 :             *guard = preload.tenant_manifest;
    1824         1404 :         }
    1825         1404 :         self.maybe_upload_tenant_manifest().await?;
    1826              : 
    1827              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1828              :         // IndexPart is the source of truth.
    1829         1404 :         self.clean_up_timelines(&existent_timelines)?;
    1830              : 
    1831         1404 :         self.gc_block.set_scanned(gc_blocks);
    1832         1404 : 
    1833         1404 :         fail::fail_point!("attach-before-activate", |_| {
    1834            0 :             anyhow::bail!("attach-before-activate");
    1835         1404 :         });
    1836         1404 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1837              : 
    1838         1404 :         info!("Done");
    1839              : 
    1840         1404 :         Ok(())
    1841         1404 :     }
    1842              : 
    1843              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1844              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1845              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1846         1404 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1847         1404 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1848              : 
    1849         1404 :         let entries = match timelines_dir.read_dir_utf8() {
    1850         1404 :             Ok(d) => d,
    1851            0 :             Err(e) => {
    1852            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1853            0 :                     return Ok(());
    1854              :                 } else {
    1855            0 :                     return Err(e).context("list timelines directory for tenant");
    1856              :                 }
    1857              :             }
    1858              :         };
    1859              : 
    1860         1452 :         for entry in entries {
    1861           48 :             let entry = entry.context("read timeline dir entry")?;
    1862           48 :             let entry_path = entry.path();
    1863              : 
    1864           48 :             let purge = if crate::is_temporary(entry_path) {
    1865            0 :                 true
    1866              :             } else {
    1867           48 :                 match TimelineId::try_from(entry_path.file_name()) {
    1868           48 :                     Ok(i) => {
    1869           48 :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1870           48 :                         !existent_timelines.contains(&i)
    1871              :                     }
    1872            0 :                     Err(e) => {
    1873            0 :                         tracing::warn!(
    1874            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1875              :                         );
    1876              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1877            0 :                         false
    1878              :                     }
    1879              :                 }
    1880              :             };
    1881              : 
    1882           48 :             if purge {
    1883           12 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1884           12 :                 if let Err(e) = match entry.file_type() {
    1885           12 :                     Ok(t) => if t.is_dir() {
    1886           12 :                         std::fs::remove_dir_all(entry_path)
    1887              :                     } else {
    1888            0 :                         std::fs::remove_file(entry_path)
    1889              :                     }
    1890           12 :                     .or_else(fs_ext::ignore_not_found),
    1891            0 :                     Err(e) => Err(e),
    1892              :                 } {
    1893            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1894           12 :                 }
    1895           36 :             }
    1896              :         }
    1897              : 
    1898         1404 :         Ok(())
    1899         1404 :     }
    1900              : 
    1901              :     /// Get sum of all remote timelines sizes
    1902              :     ///
    1903              :     /// This function relies on the index_part instead of listing the remote storage
    1904            0 :     pub fn remote_size(&self) -> u64 {
    1905            0 :         let mut size = 0;
    1906              : 
    1907            0 :         for timeline in self.list_timelines() {
    1908            0 :             size += timeline.remote_client.get_remote_physical_size();
    1909            0 :         }
    1910              : 
    1911            0 :         size
    1912            0 :     }
    1913              : 
    1914              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    1915              :     #[allow(clippy::too_many_arguments)]
    1916              :     async fn load_remote_timeline(
    1917              :         self: &Arc<Self>,
    1918              :         timeline_id: TimelineId,
    1919              :         index_part: IndexPart,
    1920              :         remote_metadata: TimelineMetadata,
    1921              :         previous_heatmap: Option<PreviousHeatmap>,
    1922              :         resources: TimelineResources,
    1923              :         cause: LoadTimelineCause,
    1924              :         ctx: &RequestContext,
    1925              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1926              :         span::debug_assert_current_span_has_tenant_id();
    1927              : 
    1928              :         info!("downloading index file for timeline {}", timeline_id);
    1929              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    1930              :             .await
    1931              :             .context("Failed to create new timeline directory")?;
    1932              : 
    1933              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    1934              :             let timelines = self.timelines.lock().unwrap();
    1935              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    1936            0 :                 || {
    1937            0 :                     anyhow::anyhow!(
    1938            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    1939            0 :                     )
    1940            0 :                 },
    1941              :             )?))
    1942              :         } else {
    1943              :             None
    1944              :         };
    1945              : 
    1946              :         self.timeline_init_and_sync(
    1947              :             timeline_id,
    1948              :             resources,
    1949              :             index_part,
    1950              :             remote_metadata,
    1951              :             previous_heatmap,
    1952              :             ancestor,
    1953              :             cause,
    1954              :             ctx,
    1955              :         )
    1956              :         .await
    1957              :     }
    1958              : 
    1959         1404 :     async fn load_timelines_metadata(
    1960         1404 :         self: &Arc<TenantShard>,
    1961         1404 :         timeline_ids: HashSet<TimelineId>,
    1962         1404 :         remote_storage: &GenericRemoteStorage,
    1963         1404 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    1964         1404 :         cancel: CancellationToken,
    1965         1404 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    1966         1404 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    1967         1404 : 
    1968         1404 :         let mut part_downloads = JoinSet::new();
    1969         1440 :         for timeline_id in timeline_ids {
    1970           36 :             let cancel_clone = cancel.clone();
    1971           36 : 
    1972           36 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    1973            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    1974            0 :                     heatmap: h,
    1975            0 :                     read_at: hs.1,
    1976            0 :                     end_lsn: None,
    1977            0 :                 })
    1978           36 :             });
    1979           36 :             part_downloads.spawn(
    1980           36 :                 self.load_timeline_metadata(
    1981           36 :                     timeline_id,
    1982           36 :                     remote_storage.clone(),
    1983           36 :                     previous_timeline_heatmap,
    1984           36 :                     cancel_clone,
    1985           36 :                 )
    1986           36 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    1987              :             );
    1988              :         }
    1989              : 
    1990         1404 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    1991              : 
    1992              :         loop {
    1993         1440 :             tokio::select!(
    1994         1440 :                 next = part_downloads.join_next() => {
    1995         1440 :                     match next {
    1996           36 :                         Some(result) => {
    1997           36 :                             let preload = result.context("join preload task")?;
    1998           36 :                             timeline_preloads.insert(preload.timeline_id, preload);
    1999              :                         },
    2000              :                         None => {
    2001         1404 :                             break;
    2002              :                         }
    2003              :                     }
    2004              :                 },
    2005         1440 :                 _ = cancel.cancelled() => {
    2006            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    2007              :                 }
    2008              :             )
    2009              :         }
    2010              : 
    2011         1404 :         Ok(timeline_preloads)
    2012         1404 :     }
    2013              : 
    2014           36 :     fn build_timeline_client(
    2015           36 :         &self,
    2016           36 :         timeline_id: TimelineId,
    2017           36 :         remote_storage: GenericRemoteStorage,
    2018           36 :     ) -> RemoteTimelineClient {
    2019           36 :         RemoteTimelineClient::new(
    2020           36 :             remote_storage.clone(),
    2021           36 :             self.deletion_queue_client.clone(),
    2022           36 :             self.conf,
    2023           36 :             self.tenant_shard_id,
    2024           36 :             timeline_id,
    2025           36 :             self.generation,
    2026           36 :             &self.tenant_conf.load().location,
    2027           36 :         )
    2028           36 :     }
    2029              : 
    2030           36 :     fn load_timeline_metadata(
    2031           36 :         self: &Arc<TenantShard>,
    2032           36 :         timeline_id: TimelineId,
    2033           36 :         remote_storage: GenericRemoteStorage,
    2034           36 :         previous_heatmap: Option<PreviousHeatmap>,
    2035           36 :         cancel: CancellationToken,
    2036           36 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2037           36 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2038           36 :         async move {
    2039           36 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2040           36 :             debug!("starting index part download");
    2041              : 
    2042           36 :             let index_part = client.download_index_file(&cancel).await;
    2043              : 
    2044           36 :             debug!("finished index part download");
    2045              : 
    2046           36 :             TimelinePreload {
    2047           36 :                 client,
    2048           36 :                 timeline_id,
    2049           36 :                 index_part,
    2050           36 :                 previous_heatmap,
    2051           36 :             }
    2052           36 :         }
    2053           36 :     }
    2054              : 
    2055            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2056            0 :         timeline_id: TimelineId,
    2057            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2058            0 :     ) -> Result<(), TimelineArchivalError> {
    2059            0 :         let children: Vec<TimelineId> = timelines
    2060            0 :             .iter()
    2061            0 :             .filter_map(|(id, entry)| {
    2062            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2063            0 :                     return None;
    2064            0 :                 }
    2065            0 :                 if entry.is_archived() == Some(true) {
    2066            0 :                     return None;
    2067            0 :                 }
    2068            0 :                 Some(*id)
    2069            0 :             })
    2070            0 :             .collect();
    2071            0 : 
    2072            0 :         if !children.is_empty() {
    2073            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2074            0 :         }
    2075            0 :         Ok(())
    2076            0 :     }
    2077              : 
    2078            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2079            0 :         ancestor_timeline_id: TimelineId,
    2080            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2081            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2082            0 :             '_,
    2083            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2084            0 :         >,
    2085            0 :     ) -> Result<(), TimelineArchivalError> {
    2086            0 :         let has_archived_parent =
    2087            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2088            0 :                 ancestor_timeline.is_archived() == Some(true)
    2089            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2090            0 :                 true
    2091              :             } else {
    2092            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2093            0 :                 if cfg!(debug_assertions) {
    2094            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2095            0 :                 }
    2096            0 :                 return Err(TimelineArchivalError::NotFound);
    2097              :             };
    2098            0 :         if has_archived_parent {
    2099            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2100            0 :                 ancestor_timeline_id,
    2101            0 :             ));
    2102            0 :         }
    2103            0 :         Ok(())
    2104            0 :     }
    2105              : 
    2106            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2107            0 :         timeline: &Arc<Timeline>,
    2108            0 :     ) -> Result<(), TimelineArchivalError> {
    2109            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2110            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2111            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2112            0 :                     ancestor_timeline.timeline_id,
    2113            0 :                 ));
    2114            0 :             }
    2115            0 :         }
    2116            0 :         Ok(())
    2117            0 :     }
    2118              : 
    2119              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2120              :     ///
    2121              :     /// Counterpart to [`offload_timeline`].
    2122            0 :     async fn unoffload_timeline(
    2123            0 :         self: &Arc<Self>,
    2124            0 :         timeline_id: TimelineId,
    2125            0 :         broker_client: storage_broker::BrokerClientChannel,
    2126            0 :         ctx: RequestContext,
    2127            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2128            0 :         info!("unoffloading timeline");
    2129              : 
    2130              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2131              :         // We expect callers of this function to ensure this.
    2132            0 :         match self.current_state() {
    2133              :             TenantState::Activating { .. }
    2134              :             | TenantState::Attaching
    2135              :             | TenantState::Broken { .. } => {
    2136            0 :                 panic!("Timeline expected to be active")
    2137              :             }
    2138            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2139            0 :             TenantState::Active => {}
    2140            0 :         }
    2141            0 :         let cancel = self.cancel.clone();
    2142            0 : 
    2143            0 :         // Protect against concurrent attempts to use this TimelineId
    2144            0 :         // We don't care much about idempotency, as it's ensured a layer above.
    2145            0 :         let allow_offloaded = true;
    2146            0 :         let _create_guard = self
    2147            0 :             .create_timeline_create_guard(
    2148            0 :                 timeline_id,
    2149            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2150            0 :                 allow_offloaded,
    2151            0 :             )
    2152            0 :             .map_err(|err| match err {
    2153            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2154              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2155            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2156              :                 }
    2157            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2158            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2159            0 :             })?;
    2160              : 
    2161            0 :         let timeline_preload = self
    2162            0 :             .load_timeline_metadata(
    2163            0 :                 timeline_id,
    2164            0 :                 self.remote_storage.clone(),
    2165            0 :                 None,
    2166            0 :                 cancel.clone(),
    2167            0 :             )
    2168            0 :             .await;
    2169              : 
    2170            0 :         let index_part = match timeline_preload.index_part {
    2171            0 :             Ok(index_part) => {
    2172            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2173            0 :                 index_part
    2174              :             }
    2175              :             Err(DownloadError::NotFound) => {
    2176            0 :                 error!(%timeline_id, "index_part not found on remote");
    2177            0 :                 return Err(TimelineArchivalError::NotFound);
    2178              :             }
    2179            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2180            0 :             Err(e) => {
    2181            0 :                 // Some (possibly ephemeral) error happened during index_part download.
    2182            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2183            0 :                 return Err(TimelineArchivalError::Other(
    2184            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2185            0 :                 ));
    2186              :             }
    2187              :         };
    2188            0 :         let index_part = match index_part {
    2189            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2190            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2191            0 :                 info!("timeline is deleted according to index_part.json");
    2192            0 :                 return Err(TimelineArchivalError::NotFound);
    2193              :             }
    2194              :         };
    2195            0 :         let remote_metadata = index_part.metadata.clone();
    2196            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2197            0 :         self.load_remote_timeline(
    2198            0 :             timeline_id,
    2199            0 :             index_part,
    2200            0 :             remote_metadata,
    2201            0 :             None,
    2202            0 :             timeline_resources,
    2203            0 :             LoadTimelineCause::Unoffload,
    2204            0 :             &ctx,
    2205            0 :         )
    2206            0 :         .await
    2207            0 :         .with_context(|| {
    2208            0 :             format!(
    2209            0 :                 "failed to load remote timeline {} for tenant {}",
    2210            0 :                 timeline_id, self.tenant_shard_id
    2211            0 :             )
    2212            0 :         })
    2213            0 :         .map_err(TimelineArchivalError::Other)?;
    2214              : 
    2215            0 :         let timeline = {
    2216            0 :             let timelines = self.timelines.lock().unwrap();
    2217            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2218            0 :                 warn!("timeline not available directly after attach");
    2219              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2220              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2221            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2222            0 :                     "timeline not available directly after attach"
    2223            0 :                 )));
    2224              :             };
    2225            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2226            0 :             match offloaded_timelines.remove(&timeline_id) {
    2227            0 :                 Some(offloaded) => {
    2228            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2229            0 :                 }
    2230            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2231              :             }
    2232              : 
    2233            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2234            0 : 
    2235            0 :             Arc::clone(timeline)
    2236            0 :         };
    2237            0 : 
    2238            0 :         // Upload new list of offloaded timelines to S3
    2239            0 :         self.maybe_upload_tenant_manifest().await?;
    2240              : 
    2241              :         // Activate the timeline (if it makes sense)
    2242            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2243            0 :             let background_jobs_can_start = None;
    2244            0 :             timeline.activate(
    2245            0 :                 self.clone(),
    2246            0 :                 broker_client.clone(),
    2247            0 :                 background_jobs_can_start,
    2248            0 :                 &ctx.with_scope_timeline(&timeline),
    2249            0 :             );
    2250            0 :         }
    2251              : 
    2252            0 :         info!("timeline unoffloading complete");
    2253            0 :         Ok(timeline)
    2254            0 :     }
    2255              : 
    2256            0 :     pub(crate) async fn apply_timeline_archival_config(
    2257            0 :         self: &Arc<Self>,
    2258            0 :         timeline_id: TimelineId,
    2259            0 :         new_state: TimelineArchivalState,
    2260            0 :         broker_client: storage_broker::BrokerClientChannel,
    2261            0 :         ctx: RequestContext,
    2262            0 :     ) -> Result<(), TimelineArchivalError> {
    2263            0 :         info!("setting timeline archival config");
    2264              :         // First part: figure out what is needed to do, and do validation
    2265            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2266            0 :             let timelines = self.timelines.lock().unwrap();
    2267              : 
    2268            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2269            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2270            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2271            0 :                     return Err(TimelineArchivalError::NotFound);
    2272              :                 };
    2273            0 :                 if new_state == TimelineArchivalState::Archived {
    2274              :                     // It's offloaded already, so nothing to do
    2275            0 :                     return Ok(());
    2276            0 :                 }
    2277            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2278            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2279            0 :                         ancestor_timeline_id,
    2280            0 :                         &timelines,
    2281            0 :                         &offloaded_timelines,
    2282            0 :                     )?;
    2283            0 :                 }
    2284            0 :                 break 'outer None;
    2285              :             };
    2286              : 
    2287              :             // Do some validation. We release the timelines lock below, so there is potential
    2288              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2289              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2290            0 :             match new_state {
    2291              :                 TimelineArchivalState::Unarchived => {
    2292            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2293              :                 }
    2294              :                 TimelineArchivalState::Archived => {
    2295            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2296              :                 }
    2297              :             }
    2298            0 :             Some(Arc::clone(timeline))
    2299              :         };
    2300              : 
    2301              :         // Second part: unoffload timeline (if needed)
    2302            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2303            0 :             timeline
    2304              :         } else {
    2305              :             // Turn offloaded timeline into a non-offloaded one
    2306            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2307            0 :                 .await?
    2308              :         };
    2309              : 
    2310              :         // Third part: upload new timeline archival state and block until it is present in S3
    2311            0 :         let upload_needed = match timeline
    2312            0 :             .remote_client
    2313            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2314              :         {
    2315            0 :             Ok(upload_needed) => upload_needed,
    2316            0 :             Err(e) => {
    2317            0 :                 if timeline.cancel.is_cancelled() {
    2318            0 :                     return Err(TimelineArchivalError::Cancelled);
    2319              :                 } else {
    2320            0 :                     return Err(TimelineArchivalError::Other(e));
    2321              :                 }
    2322              :             }
    2323              :         };
    2324              : 
    2325            0 :         if upload_needed {
    2326            0 :             info!("Uploading new state");
    2327              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2328            0 :             let Ok(v) =
    2329            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2330              :             else {
    2331            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2332            0 :                 return Err(TimelineArchivalError::Timeout);
    2333              :             };
    2334            0 :             v.map_err(|e| match e {
    2335            0 :                 WaitCompletionError::NotInitialized(e) => {
    2336            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2337              :                 }
    2338              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2339            0 :                     TimelineArchivalError::Cancelled
    2340              :                 }
    2341            0 :             })?;
    2342            0 :         }
    2343            0 :         Ok(())
    2344            0 :     }
    2345              : 
    2346           12 :     pub fn get_offloaded_timeline(
    2347           12 :         &self,
    2348           12 :         timeline_id: TimelineId,
    2349           12 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2350           12 :         self.timelines_offloaded
    2351           12 :             .lock()
    2352           12 :             .unwrap()
    2353           12 :             .get(&timeline_id)
    2354           12 :             .map(Arc::clone)
    2355           12 :             .ok_or(GetTimelineError::NotFound {
    2356           12 :                 tenant_id: self.tenant_shard_id,
    2357           12 :                 timeline_id,
    2358           12 :             })
    2359           12 :     }
    2360              : 
    2361           24 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2362           24 :         self.tenant_shard_id
    2363           24 :     }
    2364              : 
    2365              :     /// Get Timeline handle for given Neon timeline ID.
    2366              :     /// This function is idempotent. It doesn't change internal state in any way.
    2367         1332 :     pub fn get_timeline(
    2368         1332 :         &self,
    2369         1332 :         timeline_id: TimelineId,
    2370         1332 :         active_only: bool,
    2371         1332 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2372         1332 :         let timelines_accessor = self.timelines.lock().unwrap();
    2373         1332 :         let timeline = timelines_accessor
    2374         1332 :             .get(&timeline_id)
    2375         1332 :             .ok_or(GetTimelineError::NotFound {
    2376         1332 :                 tenant_id: self.tenant_shard_id,
    2377         1332 :                 timeline_id,
    2378         1332 :             })?;
    2379              : 
    2380         1320 :         if active_only && !timeline.is_active() {
    2381            0 :             Err(GetTimelineError::NotActive {
    2382            0 :                 tenant_id: self.tenant_shard_id,
    2383            0 :                 timeline_id,
    2384            0 :                 state: timeline.current_state(),
    2385            0 :             })
    2386              :         } else {
    2387         1320 :             Ok(Arc::clone(timeline))
    2388              :         }
    2389         1332 :     }
    2390              : 
    2391              :     /// Lists timelines the tenant contains.
    2392              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2393           24 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2394           24 :         self.timelines
    2395           24 :             .lock()
    2396           24 :             .unwrap()
    2397           24 :             .values()
    2398           24 :             .map(Arc::clone)
    2399           24 :             .collect()
    2400           24 :     }
    2401              : 
    2402              :     /// Lists timelines the tenant manages, including offloaded ones.
    2403              :     ///
    2404              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2405            0 :     pub fn list_timelines_and_offloaded(
    2406            0 :         &self,
    2407            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2408            0 :         let timelines = self
    2409            0 :             .timelines
    2410            0 :             .lock()
    2411            0 :             .unwrap()
    2412            0 :             .values()
    2413            0 :             .map(Arc::clone)
    2414            0 :             .collect();
    2415            0 :         let offloaded = self
    2416            0 :             .timelines_offloaded
    2417            0 :             .lock()
    2418            0 :             .unwrap()
    2419            0 :             .values()
    2420            0 :             .map(Arc::clone)
    2421            0 :             .collect();
    2422            0 :         (timelines, offloaded)
    2423            0 :     }
    2424              : 
    2425            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2426            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2427            0 :     }
    2428              : 
    2429              :     /// This is used by tests & import-from-basebackup.
    2430              :     ///
    2431              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2432              :     /// a state that will fail [`TenantShard::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2433              :     ///
    2434              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2435              :     /// by [`TenantShard::load_remote_timeline`] / [`TenantShard::attach`].
    2436              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2437              :     /// to the [`TenantShard::timelines`].
    2438              :     ///
    2439              :     /// Tests should use `TenantShard::create_test_timeline` to set up the minimum required metadata keys.
    2440         1356 :     pub(crate) async fn create_empty_timeline(
    2441         1356 :         self: &Arc<Self>,
    2442         1356 :         new_timeline_id: TimelineId,
    2443         1356 :         initdb_lsn: Lsn,
    2444         1356 :         pg_version: u32,
    2445         1356 :         ctx: &RequestContext,
    2446         1356 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2447         1356 :         anyhow::ensure!(
    2448         1356 :             self.is_active(),
    2449            0 :             "Cannot create empty timelines on inactive tenant"
    2450              :         );
    2451              : 
    2452              :         // Protect against concurrent attempts to use this TimelineId
    2453         1356 :         let create_guard = match self
    2454         1356 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2455         1356 :             .await?
    2456              :         {
    2457         1344 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2458              :             StartCreatingTimelineResult::Idempotent(_) => {
    2459            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2460              :             }
    2461              :         };
    2462              : 
    2463         1344 :         let new_metadata = TimelineMetadata::new(
    2464         1344 :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2465         1344 :             // make it valid, before calling finish_creation()
    2466         1344 :             Lsn(0),
    2467         1344 :             None,
    2468         1344 :             None,
    2469         1344 :             Lsn(0),
    2470         1344 :             initdb_lsn,
    2471         1344 :             initdb_lsn,
    2472         1344 :             pg_version,
    2473         1344 :         );
    2474         1344 :         self.prepare_new_timeline(
    2475         1344 :             new_timeline_id,
    2476         1344 :             &new_metadata,
    2477         1344 :             create_guard,
    2478         1344 :             initdb_lsn,
    2479         1344 :             None,
    2480         1344 :             None,
    2481         1344 :             ctx,
    2482         1344 :         )
    2483         1344 :         .await
    2484         1356 :     }
    2485              : 
    2486              :     /// Helper for unit tests to create an empty timeline.
    2487              :     ///
    2488              :     /// The timeline is has state value `Active` but its background loops are not running.
    2489              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2490              :     // Our current tests don't need the background loops.
    2491              :     #[cfg(test)]
    2492         1296 :     pub async fn create_test_timeline(
    2493         1296 :         self: &Arc<Self>,
    2494         1296 :         new_timeline_id: TimelineId,
    2495         1296 :         initdb_lsn: Lsn,
    2496         1296 :         pg_version: u32,
    2497         1296 :         ctx: &RequestContext,
    2498         1296 :     ) -> anyhow::Result<Arc<Timeline>> {
    2499         1296 :         let (uninit_tl, ctx) = self
    2500         1296 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2501         1296 :             .await?;
    2502         1296 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2503         1296 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2504              : 
    2505              :         // Setup minimum keys required for the timeline to be usable.
    2506         1296 :         let mut modification = tline.begin_modification(initdb_lsn);
    2507         1296 :         modification
    2508         1296 :             .init_empty_test_timeline()
    2509         1296 :             .context("init_empty_test_timeline")?;
    2510         1296 :         modification
    2511         1296 :             .commit(&ctx)
    2512         1296 :             .await
    2513         1296 :             .context("commit init_empty_test_timeline modification")?;
    2514              : 
    2515              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2516         1296 :         tline.maybe_spawn_flush_loop();
    2517         1296 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2518              : 
    2519              :         // Make sure the freeze_and_flush reaches remote storage.
    2520         1296 :         tline.remote_client.wait_completion().await.unwrap();
    2521              : 
    2522         1296 :         let tl = uninit_tl.finish_creation().await?;
    2523              :         // The non-test code would call tl.activate() here.
    2524         1296 :         tl.set_state(TimelineState::Active);
    2525         1296 :         Ok(tl)
    2526         1296 :     }
    2527              : 
    2528              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2529              :     #[cfg(test)]
    2530              :     #[allow(clippy::too_many_arguments)]
    2531          288 :     pub async fn create_test_timeline_with_layers(
    2532          288 :         self: &Arc<Self>,
    2533          288 :         new_timeline_id: TimelineId,
    2534          288 :         initdb_lsn: Lsn,
    2535          288 :         pg_version: u32,
    2536          288 :         ctx: &RequestContext,
    2537          288 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2538          288 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2539          288 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2540          288 :         end_lsn: Lsn,
    2541          288 :     ) -> anyhow::Result<Arc<Timeline>> {
    2542              :         use checks::check_valid_layermap;
    2543              :         use itertools::Itertools;
    2544              : 
    2545          288 :         let tline = self
    2546          288 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2547          288 :             .await?;
    2548          288 :         tline.force_advance_lsn(end_lsn);
    2549          852 :         for deltas in delta_layer_desc {
    2550          564 :             tline
    2551          564 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2552          564 :                 .await?;
    2553              :         }
    2554          696 :         for (lsn, images) in image_layer_desc {
    2555          408 :             tline
    2556          408 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2557          408 :                 .await?;
    2558              :         }
    2559          336 :         for in_memory in in_memory_layer_desc {
    2560           48 :             tline
    2561           48 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2562           48 :                 .await?;
    2563              :         }
    2564          288 :         let layer_names = tline
    2565          288 :             .layers
    2566          288 :             .read()
    2567          288 :             .await
    2568          288 :             .layer_map()
    2569          288 :             .unwrap()
    2570          288 :             .iter_historic_layers()
    2571         1260 :             .map(|layer| layer.layer_name())
    2572          288 :             .collect_vec();
    2573          288 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2574            0 :             bail!("invalid layermap: {err}");
    2575          288 :         }
    2576          288 :         Ok(tline)
    2577          288 :     }
    2578              : 
    2579              :     /// Create a new timeline.
    2580              :     ///
    2581              :     /// Returns the new timeline ID and reference to its Timeline object.
    2582              :     ///
    2583              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2584              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2585              :     #[allow(clippy::too_many_arguments)]
    2586            0 :     pub(crate) async fn create_timeline(
    2587            0 :         self: &Arc<TenantShard>,
    2588            0 :         params: CreateTimelineParams,
    2589            0 :         broker_client: storage_broker::BrokerClientChannel,
    2590            0 :         ctx: &RequestContext,
    2591            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2592            0 :         if !self.is_active() {
    2593            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2594            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2595              :             } else {
    2596            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2597            0 :                     "Cannot create timelines on inactive tenant"
    2598            0 :                 )));
    2599              :             }
    2600            0 :         }
    2601              : 
    2602            0 :         let _gate = self
    2603            0 :             .gate
    2604            0 :             .enter()
    2605            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2606              : 
    2607            0 :         let result: CreateTimelineResult = match params {
    2608              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2609            0 :                 new_timeline_id,
    2610            0 :                 existing_initdb_timeline_id,
    2611            0 :                 pg_version,
    2612            0 :             }) => {
    2613            0 :                 self.bootstrap_timeline(
    2614            0 :                     new_timeline_id,
    2615            0 :                     pg_version,
    2616            0 :                     existing_initdb_timeline_id,
    2617            0 :                     ctx,
    2618            0 :                 )
    2619            0 :                 .await?
    2620              :             }
    2621              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2622            0 :                 new_timeline_id,
    2623            0 :                 ancestor_timeline_id,
    2624            0 :                 mut ancestor_start_lsn,
    2625              :             }) => {
    2626            0 :                 let ancestor_timeline = self
    2627            0 :                     .get_timeline(ancestor_timeline_id, false)
    2628            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2629              : 
    2630              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2631              :                 // ready for other purposes either.
    2632            0 :                 if !ancestor_timeline.is_active() {
    2633            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2634            0 :                 }
    2635            0 : 
    2636            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2637            0 :                     info!("tried to branch archived timeline");
    2638            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2639            0 :                 }
    2640              : 
    2641            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2642            0 :                     *lsn = lsn.align();
    2643            0 : 
    2644            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2645            0 :                     if ancestor_ancestor_lsn > *lsn {
    2646              :                         // can we safely just branch from the ancestor instead?
    2647            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2648            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2649            0 :                             lsn,
    2650            0 :                             ancestor_timeline_id,
    2651            0 :                             ancestor_ancestor_lsn,
    2652            0 :                         )));
    2653            0 :                     }
    2654            0 : 
    2655            0 :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2656            0 :                     // to the requested branch point. The repository code itself doesn't
    2657            0 :                     // require it, but if we start to receive WAL on the new timeline,
    2658            0 :                     // decoding the new WAL might need to look up previous pages, relation
    2659            0 :                     // sizes etc. and that would get confused if the previous page versions
    2660            0 :                     // are not in the repository yet.
    2661            0 :                     ancestor_timeline
    2662            0 :                         .wait_lsn(
    2663            0 :                             *lsn,
    2664            0 :                             timeline::WaitLsnWaiter::Tenant,
    2665            0 :                             timeline::WaitLsnTimeout::Default,
    2666            0 :                             ctx,
    2667            0 :                         )
    2668            0 :                         .await
    2669            0 :                         .map_err(|e| match e {
    2670            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2671            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2672              :                             }
    2673            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2674            0 :                         })?;
    2675            0 :                 }
    2676              : 
    2677            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2678            0 :                     .await?
    2679              :             }
    2680            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2681            0 :                 self.create_timeline_import_pgdata(
    2682            0 :                     params,
    2683            0 :                     ActivateTimelineArgs::Yes {
    2684            0 :                         broker_client: broker_client.clone(),
    2685            0 :                     },
    2686            0 :                     ctx,
    2687            0 :                 )
    2688            0 :                 .await?
    2689              :             }
    2690              :         };
    2691              : 
    2692              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2693              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2694              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2695              :         //
    2696              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2697              :         // assume that, because they can see the timeline via API, that the creation is done and
    2698              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2699              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2700              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2701              :         //
    2702              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2703              :         // creation API until it returns success. Only then is durability guaranteed.
    2704            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2705            0 :         result
    2706            0 :             .timeline()
    2707            0 :             .remote_client
    2708            0 :             .wait_completion()
    2709            0 :             .await
    2710            0 :             .map_err(|e| match e {
    2711              :                 WaitCompletionError::NotInitialized(
    2712            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2713            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2714              :                 WaitCompletionError::NotInitialized(_) => {
    2715              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2716            0 :                     debug_assert!(false);
    2717            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2718              :                 }
    2719              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2720            0 :                     CreateTimelineError::ShuttingDown
    2721              :                 }
    2722            0 :             })?;
    2723              : 
    2724              :         // The creating task is responsible for activating the timeline.
    2725              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2726              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2727            0 :         let activated_timeline = match result {
    2728            0 :             CreateTimelineResult::Created(timeline) => {
    2729            0 :                 timeline.activate(
    2730            0 :                     self.clone(),
    2731            0 :                     broker_client,
    2732            0 :                     None,
    2733            0 :                     &ctx.with_scope_timeline(&timeline),
    2734            0 :                 );
    2735            0 :                 timeline
    2736              :             }
    2737            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2738            0 :                 info!(
    2739            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2740              :                 );
    2741            0 :                 timeline
    2742              :             }
    2743            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2744            0 :                 info!(
    2745            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2746              :                 );
    2747            0 :                 timeline
    2748              :             }
    2749              :         };
    2750              : 
    2751            0 :         Ok(activated_timeline)
    2752            0 :     }
    2753              : 
    2754              :     /// The returned [`Arc<Timeline>`] is NOT in the [`TenantShard::timelines`] map until the import
    2755              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2756              :     /// [`TenantShard::timelines`] map when the import completes.
    2757              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2758              :     /// for the response.
    2759            0 :     async fn create_timeline_import_pgdata(
    2760            0 :         self: &Arc<Self>,
    2761            0 :         params: CreateTimelineParamsImportPgdata,
    2762            0 :         activate: ActivateTimelineArgs,
    2763            0 :         ctx: &RequestContext,
    2764            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2765            0 :         let CreateTimelineParamsImportPgdata {
    2766            0 :             new_timeline_id,
    2767            0 :             location,
    2768            0 :             idempotency_key,
    2769            0 :         } = params;
    2770            0 : 
    2771            0 :         let started_at = chrono::Utc::now().naive_utc();
    2772              : 
    2773              :         //
    2774              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2775              :         // is the canonical way we do it.
    2776              :         // - create an empty timeline in-memory
    2777              :         // - use its remote_timeline_client to do the upload
    2778              :         // - dispose of the uninit timeline
    2779              :         // - keep the creation guard alive
    2780              : 
    2781            0 :         let timeline_create_guard = match self
    2782            0 :             .start_creating_timeline(
    2783            0 :                 new_timeline_id,
    2784            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2785            0 :                     idempotency_key: idempotency_key.clone(),
    2786            0 :                 }),
    2787            0 :             )
    2788            0 :             .await?
    2789              :         {
    2790            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2791            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2792            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2793              :             }
    2794              :         };
    2795              : 
    2796            0 :         let (mut uninit_timeline, timeline_ctx) = {
    2797            0 :             let this = &self;
    2798            0 :             let initdb_lsn = Lsn(0);
    2799            0 :             async move {
    2800            0 :                 let new_metadata = TimelineMetadata::new(
    2801            0 :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2802            0 :                     // make it valid, before calling finish_creation()
    2803            0 :                     Lsn(0),
    2804            0 :                     None,
    2805            0 :                     None,
    2806            0 :                     Lsn(0),
    2807            0 :                     initdb_lsn,
    2808            0 :                     initdb_lsn,
    2809            0 :                     15,
    2810            0 :                 );
    2811            0 :                 this.prepare_new_timeline(
    2812            0 :                     new_timeline_id,
    2813            0 :                     &new_metadata,
    2814            0 :                     timeline_create_guard,
    2815            0 :                     initdb_lsn,
    2816            0 :                     None,
    2817            0 :                     None,
    2818            0 :                     ctx,
    2819            0 :                 )
    2820            0 :                 .await
    2821            0 :             }
    2822            0 :         }
    2823            0 :         .await?;
    2824              : 
    2825            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2826            0 :             idempotency_key,
    2827            0 :             location,
    2828            0 :             started_at,
    2829            0 :         };
    2830            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2831            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2832            0 :         );
    2833            0 :         uninit_timeline
    2834            0 :             .raw_timeline()
    2835            0 :             .unwrap()
    2836            0 :             .remote_client
    2837            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2838              : 
    2839              :         // wait_completion happens in caller
    2840              : 
    2841            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2842            0 : 
    2843            0 :         tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2844            0 :             timeline.clone(),
    2845            0 :             index_part,
    2846            0 :             activate,
    2847            0 :             timeline_create_guard,
    2848            0 :             timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    2849            0 :         ));
    2850            0 : 
    2851            0 :         // NB: the timeline doesn't exist in self.timelines at this point
    2852            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2853            0 :     }
    2854              : 
    2855              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))]
    2856              :     async fn create_timeline_import_pgdata_task(
    2857              :         self: Arc<TenantShard>,
    2858              :         timeline: Arc<Timeline>,
    2859              :         index_part: import_pgdata::index_part_format::Root,
    2860              :         activate: ActivateTimelineArgs,
    2861              :         timeline_create_guard: TimelineCreateGuard,
    2862              :         ctx: RequestContext,
    2863              :     ) {
    2864              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2865              :         info!("starting");
    2866              :         scopeguard::defer! {info!("exiting")};
    2867              : 
    2868              :         let res = self
    2869              :             .create_timeline_import_pgdata_task_impl(
    2870              :                 timeline,
    2871              :                 index_part,
    2872              :                 activate,
    2873              :                 timeline_create_guard,
    2874              :                 ctx,
    2875              :             )
    2876              :             .await;
    2877              :         if let Err(err) = &res {
    2878              :             error!(?err, "task failed");
    2879              :             // TODO sleep & retry, sensitive to tenant shutdown
    2880              :             // TODO: allow timeline deletion requests => should cancel the task
    2881              :         }
    2882              :     }
    2883              : 
    2884            0 :     async fn create_timeline_import_pgdata_task_impl(
    2885            0 :         self: Arc<TenantShard>,
    2886            0 :         timeline: Arc<Timeline>,
    2887            0 :         index_part: import_pgdata::index_part_format::Root,
    2888            0 :         activate: ActivateTimelineArgs,
    2889            0 :         timeline_create_guard: TimelineCreateGuard,
    2890            0 :         ctx: RequestContext,
    2891            0 :     ) -> Result<(), anyhow::Error> {
    2892            0 :         info!("importing pgdata");
    2893            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    2894            0 :             .await
    2895            0 :             .context("import")?;
    2896            0 :         info!("import done");
    2897              : 
    2898              :         //
    2899              :         // Reload timeline from remote.
    2900              :         // This proves that the remote state is attachable, and it reuses the code.
    2901              :         //
    2902              :         // TODO: think about whether this is safe to do with concurrent TenantShard::shutdown.
    2903              :         // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
    2904              :         // But our activate() call might launch new background tasks after TenantShard::shutdown
    2905              :         // already went past shutting down the TenantShard::timelines, which this timeline here is no part of.
    2906              :         // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
    2907              :         // down while bootstrapping/branching + activating), but, the race condition is much more likely
    2908              :         // to manifest because of the long runtime of this import task.
    2909              : 
    2910              :         //        in theory this shouldn't even .await anything except for coop yield
    2911            0 :         info!("shutting down timeline");
    2912            0 :         timeline.shutdown(ShutdownMode::Hard).await;
    2913            0 :         info!("timeline shut down, reloading from remote");
    2914              :         // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
    2915              :         // let Some(timeline) = Arc::into_inner(timeline) else {
    2916              :         //     anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
    2917              :         // };
    2918            0 :         let timeline_id = timeline.timeline_id;
    2919            0 : 
    2920            0 :         // load from object storage like TenantShard::attach does
    2921            0 :         let resources = self.build_timeline_resources(timeline_id);
    2922            0 :         let index_part = resources
    2923            0 :             .remote_client
    2924            0 :             .download_index_file(&self.cancel)
    2925            0 :             .await?;
    2926            0 :         let index_part = match index_part {
    2927              :             MaybeDeletedIndexPart::Deleted(_) => {
    2928              :                 // likely concurrent delete call, cplane should prevent this
    2929            0 :                 anyhow::bail!(
    2930            0 :                     "index part says deleted but we are not done creating yet, this should not happen but"
    2931            0 :                 )
    2932              :             }
    2933            0 :             MaybeDeletedIndexPart::IndexPart(p) => p,
    2934            0 :         };
    2935            0 :         let metadata = index_part.metadata.clone();
    2936            0 :         self
    2937            0 :             .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
    2938            0 :                 create_guard: timeline_create_guard, activate, }, &ctx)
    2939            0 :             .await?
    2940            0 :             .ready_to_activate()
    2941            0 :             .context("implementation error: reloaded timeline still needs import after import reported success")?;
    2942              : 
    2943            0 :         anyhow::Ok(())
    2944            0 :     }
    2945              : 
    2946            0 :     pub(crate) async fn delete_timeline(
    2947            0 :         self: Arc<Self>,
    2948            0 :         timeline_id: TimelineId,
    2949            0 :     ) -> Result<(), DeleteTimelineError> {
    2950            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    2951              : 
    2952            0 :         Ok(())
    2953            0 :     }
    2954              : 
    2955              :     /// perform one garbage collection iteration, removing old data files from disk.
    2956              :     /// this function is periodically called by gc task.
    2957              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    2958              :     ///
    2959              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    2960              :     ///
    2961              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    2962              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    2963              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    2964              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    2965              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    2966              :     /// requires more history to be retained.
    2967              :     //
    2968         4524 :     pub(crate) async fn gc_iteration(
    2969         4524 :         &self,
    2970         4524 :         target_timeline_id: Option<TimelineId>,
    2971         4524 :         horizon: u64,
    2972         4524 :         pitr: Duration,
    2973         4524 :         cancel: &CancellationToken,
    2974         4524 :         ctx: &RequestContext,
    2975         4524 :     ) -> Result<GcResult, GcError> {
    2976         4524 :         // Don't start doing work during shutdown
    2977         4524 :         if let TenantState::Stopping { .. } = self.current_state() {
    2978            0 :             return Ok(GcResult::default());
    2979         4524 :         }
    2980         4524 : 
    2981         4524 :         // there is a global allowed_error for this
    2982         4524 :         if !self.is_active() {
    2983            0 :             return Err(GcError::NotActive);
    2984         4524 :         }
    2985         4524 : 
    2986         4524 :         {
    2987         4524 :             let conf = self.tenant_conf.load();
    2988         4524 : 
    2989         4524 :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    2990         4524 :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    2991         4524 :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    2992         4524 :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    2993         4524 :             if !conf.location.may_delete_layers_hint() {
    2994            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    2995            0 :                 return Ok(GcResult::default());
    2996         4524 :             }
    2997         4524 : 
    2998         4524 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    2999         4500 :                 info!("Skipping GC because lsn lease deadline is not reached");
    3000         4500 :                 return Ok(GcResult::default());
    3001           24 :             }
    3002              :         }
    3003              : 
    3004           24 :         let _guard = match self.gc_block.start().await {
    3005           24 :             Ok(guard) => guard,
    3006            0 :             Err(reasons) => {
    3007            0 :                 info!("Skipping GC: {reasons}");
    3008            0 :                 return Ok(GcResult::default());
    3009              :             }
    3010              :         };
    3011              : 
    3012           24 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3013           24 :             .await
    3014         4524 :     }
    3015              : 
    3016              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    3017              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    3018              :     /// immediate L0 compaction.
    3019              :     ///
    3020              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    3021            0 :     async fn compaction_iteration(
    3022            0 :         self: &Arc<Self>,
    3023            0 :         cancel: &CancellationToken,
    3024            0 :         ctx: &RequestContext,
    3025            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    3026            0 :         // Don't compact inactive tenants.
    3027            0 :         if !self.is_active() {
    3028            0 :             return Ok(CompactionOutcome::Skipped);
    3029            0 :         }
    3030            0 : 
    3031            0 :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    3032            0 :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    3033            0 :         let location = self.tenant_conf.load().location;
    3034            0 :         if !location.may_upload_layers_hint() {
    3035            0 :             info!("skipping compaction in location state {location:?}");
    3036            0 :             return Ok(CompactionOutcome::Skipped);
    3037            0 :         }
    3038            0 : 
    3039            0 :         // Don't compact if the circuit breaker is tripped.
    3040            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3041            0 :             info!("skipping compaction due to previous failures");
    3042            0 :             return Ok(CompactionOutcome::Skipped);
    3043            0 :         }
    3044            0 : 
    3045            0 :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3046            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3047            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3048            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3049            0 : 
    3050            0 :         {
    3051            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3052            0 :             let timelines = self.timelines.lock().unwrap();
    3053            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3054              :                 // Skip inactive timelines.
    3055            0 :                 if !timeline.is_active() {
    3056            0 :                     continue;
    3057            0 :                 }
    3058            0 : 
    3059            0 :                 // Schedule the timeline for compaction.
    3060            0 :                 compact.push(timeline.clone());
    3061              : 
    3062              :                 // Schedule the timeline for offloading if eligible.
    3063            0 :                 let can_offload = offload_enabled
    3064            0 :                     && timeline.can_offload().0
    3065            0 :                     && !timelines
    3066            0 :                         .iter()
    3067            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3068            0 :                 if can_offload {
    3069            0 :                     offload.insert(timeline_id);
    3070            0 :                 }
    3071              :             }
    3072              :         } // release timelines lock
    3073              : 
    3074            0 :         for timeline in &compact {
    3075              :             // Collect L0 counts. Can't await while holding lock above.
    3076            0 :             if let Ok(lm) = timeline.layers.read().await.layer_map() {
    3077            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3078            0 :             }
    3079              :         }
    3080              : 
    3081              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3082              :         // bound read amplification.
    3083              :         //
    3084              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3085              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3086              :         // splitting L0 and image/GC compaction to separate background jobs.
    3087            0 :         if self.get_compaction_l0_first() {
    3088            0 :             let compaction_threshold = self.get_compaction_threshold();
    3089            0 :             let compact_l0 = compact
    3090            0 :                 .iter()
    3091            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3092            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3093            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3094            0 :                 .rev()
    3095            0 :                 .map(|(tli, _)| tli.clone())
    3096            0 :                 .collect_vec();
    3097            0 : 
    3098            0 :             let mut has_pending_l0 = false;
    3099            0 :             for timeline in compact_l0 {
    3100            0 :                 let ctx = &ctx.with_scope_timeline(&timeline);
    3101              :                 // NB: don't set CompactFlags::YieldForL0, since this is an L0-only compaction pass.
    3102            0 :                 let outcome = timeline
    3103            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3104            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3105            0 :                     .await
    3106            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3107            0 :                 match outcome {
    3108            0 :                     CompactionOutcome::Done => {}
    3109            0 :                     CompactionOutcome::Skipped => {}
    3110            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3111            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3112              :                 }
    3113              :             }
    3114            0 :             if has_pending_l0 {
    3115            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3116            0 :             }
    3117            0 :         }
    3118              : 
    3119              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated more
    3120              :         // L0 layers, they may also be compacted here. Image compaction will yield if there is
    3121              :         // pending L0 compaction on any tenant timeline.
    3122              :         //
    3123              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3124              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3125            0 :         let mut has_pending = false;
    3126            0 :         for timeline in compact {
    3127            0 :             if !timeline.is_active() {
    3128            0 :                 continue;
    3129            0 :             }
    3130            0 :             let ctx = &ctx.with_scope_timeline(&timeline);
    3131            0 : 
    3132            0 :             // Yield for L0 if the separate L0 pass is enabled (otherwise there's no point).
    3133            0 :             let mut flags = EnumSet::default();
    3134            0 :             if self.get_compaction_l0_first() {
    3135            0 :                 flags |= CompactFlags::YieldForL0;
    3136            0 :             }
    3137              : 
    3138            0 :             let mut outcome = timeline
    3139            0 :                 .compact(cancel, flags, ctx)
    3140            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3141            0 :                 .await
    3142            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3143              : 
    3144              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3145            0 :             if outcome == CompactionOutcome::Done {
    3146            0 :                 let queue = {
    3147            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3148            0 :                     guard
    3149            0 :                         .entry(timeline.timeline_id)
    3150            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3151            0 :                         .clone()
    3152            0 :                 };
    3153            0 :                 outcome = queue
    3154            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3155            0 :                     .instrument(
    3156            0 :                         info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
    3157              :                     )
    3158            0 :                     .await?;
    3159            0 :             }
    3160              : 
    3161              :             // If we're done compacting, offload the timeline if requested.
    3162            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3163            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3164            0 :                 offload_timeline(self, &timeline)
    3165            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3166            0 :                     .await
    3167            0 :                     .or_else(|err| match err {
    3168              :                         // Ignore this, we likely raced with unarchival.
    3169            0 :                         OffloadError::NotArchived => Ok(()),
    3170            0 :                         err => Err(err),
    3171            0 :                     })?;
    3172            0 :             }
    3173              : 
    3174            0 :             match outcome {
    3175            0 :                 CompactionOutcome::Done => {}
    3176            0 :                 CompactionOutcome::Skipped => {}
    3177            0 :                 CompactionOutcome::Pending => has_pending = true,
    3178              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3179              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3180            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3181              :             }
    3182              :         }
    3183              : 
    3184              :         // Success! Untrip the breaker if necessary.
    3185            0 :         self.compaction_circuit_breaker
    3186            0 :             .lock()
    3187            0 :             .unwrap()
    3188            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3189            0 : 
    3190            0 :         match has_pending {
    3191            0 :             true => Ok(CompactionOutcome::Pending),
    3192            0 :             false => Ok(CompactionOutcome::Done),
    3193              :         }
    3194            0 :     }
    3195              : 
    3196              :     /// Trips the compaction circuit breaker if appropriate.
    3197            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3198            0 :         match err {
    3199            0 :             err if err.is_cancel() => {}
    3200            0 :             CompactionError::ShuttingDown => (),
    3201              :             // Offload failures don't trip the circuit breaker, since they're cheap to retry and
    3202              :             // shouldn't block compaction.
    3203            0 :             CompactionError::Offload(_) => {}
    3204            0 :             CompactionError::CollectKeySpaceError(err) => {
    3205            0 :                 // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
    3206            0 :                 self.compaction_circuit_breaker
    3207            0 :                     .lock()
    3208            0 :                     .unwrap()
    3209            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3210            0 :             }
    3211            0 :             CompactionError::Other(err) => {
    3212            0 :                 self.compaction_circuit_breaker
    3213            0 :                     .lock()
    3214            0 :                     .unwrap()
    3215            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3216            0 :             }
    3217            0 :             CompactionError::AlreadyRunning(_) => {}
    3218              :         }
    3219            0 :     }
    3220              : 
    3221              :     /// Cancel scheduled compaction tasks
    3222            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3223            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3224            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3225            0 :             q.cancel_scheduled();
    3226            0 :         }
    3227            0 :     }
    3228              : 
    3229            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3230            0 :         &self,
    3231            0 :         timeline_id: TimelineId,
    3232            0 :     ) -> Vec<CompactInfoResponse> {
    3233            0 :         let res = {
    3234            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3235            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3236              :         };
    3237            0 :         let Some((running, remaining)) = res else {
    3238            0 :             return Vec::new();
    3239              :         };
    3240            0 :         let mut result = Vec::new();
    3241            0 :         if let Some((id, running)) = running {
    3242            0 :             result.extend(running.into_compact_info_resp(id, true));
    3243            0 :         }
    3244            0 :         for (id, job) in remaining {
    3245            0 :             result.extend(job.into_compact_info_resp(id, false));
    3246            0 :         }
    3247            0 :         result
    3248            0 :     }
    3249              : 
    3250              :     /// Schedule a compaction task for a timeline.
    3251            0 :     pub(crate) async fn schedule_compaction(
    3252            0 :         &self,
    3253            0 :         timeline_id: TimelineId,
    3254            0 :         options: CompactOptions,
    3255            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3256            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3257            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3258            0 :         let q = guard
    3259            0 :             .entry(timeline_id)
    3260            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3261            0 :         q.schedule_manual_compaction(options, Some(tx));
    3262            0 :         Ok(rx)
    3263            0 :     }
    3264              : 
    3265              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3266            0 :     async fn housekeeping(&self) {
    3267            0 :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3268            0 :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3269            0 :         //
    3270            0 :         // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
    3271            0 :         // We don't run compaction in this case either, and don't want to keep flushing tiny L0
    3272            0 :         // layers that won't be compacted down.
    3273            0 :         if self.tenant_conf.load().location.may_upload_layers_hint() {
    3274            0 :             let timelines = self
    3275            0 :                 .timelines
    3276            0 :                 .lock()
    3277            0 :                 .unwrap()
    3278            0 :                 .values()
    3279            0 :                 .filter(|tli| tli.is_active())
    3280            0 :                 .cloned()
    3281            0 :                 .collect_vec();
    3282              : 
    3283            0 :             for timeline in timelines {
    3284            0 :                 timeline.maybe_freeze_ephemeral_layer().await;
    3285              :             }
    3286            0 :         }
    3287              : 
    3288              :         // Shut down walredo if idle.
    3289              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3290            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3291            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3292            0 :         }
    3293            0 :     }
    3294              : 
    3295            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3296            0 :         let timelines = self.timelines.lock().unwrap();
    3297            0 :         !timelines
    3298            0 :             .iter()
    3299            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3300            0 :     }
    3301              : 
    3302        10500 :     pub fn current_state(&self) -> TenantState {
    3303        10500 :         self.state.borrow().clone()
    3304        10500 :     }
    3305              : 
    3306         5928 :     pub fn is_active(&self) -> bool {
    3307         5928 :         self.current_state() == TenantState::Active
    3308         5928 :     }
    3309              : 
    3310            0 :     pub fn generation(&self) -> Generation {
    3311            0 :         self.generation
    3312            0 :     }
    3313              : 
    3314            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3315            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3316            0 :     }
    3317              : 
    3318              :     /// Changes tenant status to active, unless shutdown was already requested.
    3319              :     ///
    3320              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3321              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3322            0 :     fn activate(
    3323            0 :         self: &Arc<Self>,
    3324            0 :         broker_client: BrokerClientChannel,
    3325            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3326            0 :         ctx: &RequestContext,
    3327            0 :     ) {
    3328            0 :         span::debug_assert_current_span_has_tenant_id();
    3329            0 : 
    3330            0 :         let mut activating = false;
    3331            0 :         self.state.send_modify(|current_state| {
    3332              :             use pageserver_api::models::ActivatingFrom;
    3333            0 :             match &*current_state {
    3334              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3335            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
    3336              :                 }
    3337            0 :                 TenantState::Attaching => {
    3338            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3339            0 :                 }
    3340            0 :             }
    3341            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3342            0 :             activating = true;
    3343            0 :             // Continue outside the closure. We need to grab timelines.lock()
    3344            0 :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3345            0 :         });
    3346            0 : 
    3347            0 :         if activating {
    3348            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3349            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3350            0 :             let timelines_to_activate = timelines_accessor
    3351            0 :                 .values()
    3352            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3353            0 : 
    3354            0 :             // Before activation, populate each Timeline's GcInfo with information about its children
    3355            0 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    3356            0 : 
    3357            0 :             // Spawn gc and compaction loops. The loops will shut themselves
    3358            0 :             // down when they notice that the tenant is inactive.
    3359            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3360            0 : 
    3361            0 :             let mut activated_timelines = 0;
    3362              : 
    3363            0 :             for timeline in timelines_to_activate {
    3364            0 :                 timeline.activate(
    3365            0 :                     self.clone(),
    3366            0 :                     broker_client.clone(),
    3367            0 :                     background_jobs_can_start,
    3368            0 :                     &ctx.with_scope_timeline(timeline),
    3369            0 :                 );
    3370            0 :                 activated_timelines += 1;
    3371            0 :             }
    3372              : 
    3373            0 :             self.state.send_modify(move |current_state| {
    3374            0 :                 assert!(
    3375            0 :                     matches!(current_state, TenantState::Activating(_)),
    3376            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3377              :                 );
    3378            0 :                 *current_state = TenantState::Active;
    3379            0 : 
    3380            0 :                 let elapsed = self.constructed_at.elapsed();
    3381            0 :                 let total_timelines = timelines_accessor.len();
    3382            0 : 
    3383            0 :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3384            0 :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3385            0 :                 info!(
    3386            0 :                     since_creation_millis = elapsed.as_millis(),
    3387            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3388            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3389            0 :                     activated_timelines,
    3390            0 :                     total_timelines,
    3391            0 :                     post_state = <&'static str>::from(&*current_state),
    3392            0 :                     "activation attempt finished"
    3393              :                 );
    3394              : 
    3395            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3396            0 :             });
    3397            0 :         }
    3398            0 :     }
    3399              : 
    3400              :     /// Shutdown the tenant and join all of the spawned tasks.
    3401              :     ///
    3402              :     /// The method caters for all use-cases:
    3403              :     /// - pageserver shutdown (freeze_and_flush == true)
    3404              :     /// - detach + ignore (freeze_and_flush == false)
    3405              :     ///
    3406              :     /// This will attempt to shutdown even if tenant is broken.
    3407              :     ///
    3408              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3409              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3410              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3411              :     /// the ongoing shutdown.
    3412           36 :     async fn shutdown(
    3413           36 :         &self,
    3414           36 :         shutdown_progress: completion::Barrier,
    3415           36 :         shutdown_mode: timeline::ShutdownMode,
    3416           36 :     ) -> Result<(), completion::Barrier> {
    3417           36 :         span::debug_assert_current_span_has_tenant_id();
    3418              : 
    3419              :         // Set tenant (and its timlines) to Stoppping state.
    3420              :         //
    3421              :         // Since we can only transition into Stopping state after activation is complete,
    3422              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3423              :         //
    3424              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3425              :         // 1. Lock out any new requests to the tenants.
    3426              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3427              :         // 3. Signal cancellation for other tenant background loops.
    3428              :         // 4. ???
    3429              :         //
    3430              :         // The waiting for the cancellation is not done uniformly.
    3431              :         // We certainly wait for WAL receivers to shut down.
    3432              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3433              :         // But the tenant background loops are joined-on in our caller.
    3434              :         // It's mesed up.
    3435              :         // we just ignore the failure to stop
    3436              : 
    3437              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3438              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3439              :         // is very slow.
    3440           36 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3441            0 :             self.cancel.cancel();
    3442            0 : 
    3443            0 :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3444            0 :             // are children of ours, so their flush loops will have shut down already
    3445            0 :             timeline::ShutdownMode::Hard
    3446              :         } else {
    3447           36 :             shutdown_mode
    3448              :         };
    3449              : 
    3450           36 :         match self.set_stopping(shutdown_progress).await {
    3451           36 :             Ok(()) => {}
    3452            0 :             Err(SetStoppingError::Broken) => {
    3453            0 :                 // assume that this is acceptable
    3454            0 :             }
    3455            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3456            0 :                 // give caller the option to wait for this this shutdown
    3457            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3458            0 :                 return Err(other);
    3459              :             }
    3460              :         };
    3461              : 
    3462           36 :         let mut js = tokio::task::JoinSet::new();
    3463           36 :         {
    3464           36 :             let timelines = self.timelines.lock().unwrap();
    3465           36 :             timelines.values().for_each(|timeline| {
    3466           36 :                 let timeline = Arc::clone(timeline);
    3467           36 :                 let timeline_id = timeline.timeline_id;
    3468           36 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3469           36 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3470           36 :             });
    3471           36 :         }
    3472           36 :         {
    3473           36 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3474           36 :             timelines_offloaded.values().for_each(|timeline| {
    3475            0 :                 timeline.defuse_for_tenant_drop();
    3476           36 :             });
    3477           36 :         }
    3478           36 :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3479           36 :         tracing::info!("Waiting for timelines...");
    3480           72 :         while let Some(res) = js.join_next().await {
    3481            0 :             match res {
    3482           36 :                 Ok(()) => {}
    3483            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3484            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3485            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3486              :             }
    3487              :         }
    3488              : 
    3489           36 :         if let ShutdownMode::Reload = shutdown_mode {
    3490            0 :             tracing::info!("Flushing deletion queue");
    3491            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3492            0 :                 match e {
    3493            0 :                     DeletionQueueError::ShuttingDown => {
    3494            0 :                         // This is the only error we expect for now. In the future, if more error
    3495            0 :                         // variants are added, we should handle them here.
    3496            0 :                     }
    3497              :                 }
    3498            0 :             }
    3499           36 :         }
    3500              : 
    3501              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3502              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3503           36 :         tracing::debug!("Cancelling CancellationToken");
    3504           36 :         self.cancel.cancel();
    3505           36 : 
    3506           36 :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3507           36 :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3508           36 :         //
    3509           36 :         // this will additionally shutdown and await all timeline tasks.
    3510           36 :         tracing::debug!("Waiting for tasks...");
    3511           36 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3512              : 
    3513           36 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3514           36 :             walredo_mgr.shutdown().await;
    3515            0 :         }
    3516              : 
    3517              :         // Wait for any in-flight operations to complete
    3518           36 :         self.gate.close().await;
    3519              : 
    3520           36 :         remove_tenant_metrics(&self.tenant_shard_id);
    3521           36 : 
    3522           36 :         Ok(())
    3523           36 :     }
    3524              : 
    3525              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3526              :     ///
    3527              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3528              :     ///
    3529              :     /// This function is not cancel-safe!
    3530           36 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3531           36 :         let mut rx = self.state.subscribe();
    3532           36 : 
    3533           36 :         // cannot stop before we're done activating, so wait out until we're done activating
    3534           36 :         rx.wait_for(|state| match state {
    3535              :             TenantState::Activating(_) | TenantState::Attaching => {
    3536            0 :                 info!("waiting for {state} to turn Active|Broken|Stopping");
    3537            0 :                 false
    3538              :             }
    3539           36 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3540           36 :         })
    3541           36 :         .await
    3542           36 :         .expect("cannot drop self.state while on a &self method");
    3543           36 : 
    3544           36 :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3545           36 :         let mut err = None;
    3546           36 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3547              :             TenantState::Activating(_) | TenantState::Attaching => {
    3548            0 :                 unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3549              :             }
    3550              :             TenantState::Active => {
    3551              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3552              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3553              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3554           36 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3555           36 :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3556           36 :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3557           36 :                 true
    3558              :             }
    3559              :             TenantState::Stopping { progress: None } => {
    3560              :                 // An attach was cancelled, and the attach transitioned the tenant from Attaching to
    3561              :                 // Stopping(None) to let us know it exited. Register our progress and continue.
    3562            0 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3563            0 :                 true
    3564              :             }
    3565            0 :             TenantState::Broken { reason, .. } => {
    3566            0 :                 info!(
    3567            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3568              :                 );
    3569            0 :                 err = Some(SetStoppingError::Broken);
    3570            0 :                 false
    3571              :             }
    3572            0 :             TenantState::Stopping { progress: Some(progress) } => {
    3573            0 :                 info!("Tenant is already in Stopping state");
    3574            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3575            0 :                 false
    3576              :             }
    3577           36 :         });
    3578           36 :         match (stopping, err) {
    3579           36 :             (true, None) => {} // continue
    3580            0 :             (false, Some(err)) => return Err(err),
    3581            0 :             (true, Some(_)) => unreachable!(
    3582            0 :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3583            0 :             ),
    3584            0 :             (false, None) => unreachable!(
    3585            0 :                 "send_if_modified closure must return true if transitioning to Stopping"
    3586            0 :             ),
    3587              :         }
    3588              : 
    3589           36 :         let timelines_accessor = self.timelines.lock().unwrap();
    3590           36 :         let not_broken_timelines = timelines_accessor
    3591           36 :             .values()
    3592           36 :             .filter(|timeline| !timeline.is_broken());
    3593           72 :         for timeline in not_broken_timelines {
    3594           36 :             timeline.set_state(TimelineState::Stopping);
    3595           36 :         }
    3596           36 :         Ok(())
    3597           36 :     }
    3598              : 
    3599              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3600              :     /// `remove_tenant_from_memory`
    3601              :     ///
    3602              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3603              :     ///
    3604              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3605            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3606            0 :         let mut rx = self.state.subscribe();
    3607            0 : 
    3608            0 :         // The load & attach routines own the tenant state until it has reached `Active`.
    3609            0 :         // So, wait until it's done.
    3610            0 :         rx.wait_for(|state| match state {
    3611              :             TenantState::Activating(_) | TenantState::Attaching => {
    3612            0 :                 info!(
    3613            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3614            0 :                     <&'static str>::from(state)
    3615              :                 );
    3616            0 :                 false
    3617              :             }
    3618            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3619            0 :         })
    3620            0 :         .await
    3621            0 :         .expect("cannot drop self.state while on a &self method");
    3622            0 : 
    3623            0 :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3624            0 :         self.set_broken_no_wait(reason)
    3625            0 :     }
    3626              : 
    3627            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3628            0 :         let reason = reason.to_string();
    3629            0 :         self.state.send_modify(|current_state| {
    3630            0 :             match *current_state {
    3631              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3632            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3633              :                 }
    3634              :                 TenantState::Active => {
    3635            0 :                     if cfg!(feature = "testing") {
    3636            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3637            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3638              :                     } else {
    3639            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3640              :                     }
    3641              :                 }
    3642              :                 TenantState::Broken { .. } => {
    3643            0 :                     warn!("Tenant is already in Broken state");
    3644              :                 }
    3645              :                 // This is the only "expected" path, any other path is a bug.
    3646              :                 TenantState::Stopping { .. } => {
    3647            0 :                     warn!(
    3648            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3649              :                         reason
    3650              :                     );
    3651            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3652              :                 }
    3653              :            }
    3654            0 :         });
    3655            0 :     }
    3656              : 
    3657            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3658            0 :         self.state.subscribe()
    3659            0 :     }
    3660              : 
    3661              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3662              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3663            0 :     pub(crate) fn activate_now(&self) {
    3664            0 :         self.activate_now_sem.add_permits(1);
    3665            0 :     }
    3666              : 
    3667            0 :     pub(crate) async fn wait_to_become_active(
    3668            0 :         &self,
    3669            0 :         timeout: Duration,
    3670            0 :     ) -> Result<(), GetActiveTenantError> {
    3671            0 :         let mut receiver = self.state.subscribe();
    3672              :         loop {
    3673            0 :             let current_state = receiver.borrow_and_update().clone();
    3674            0 :             match current_state {
    3675              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3676              :                     // in these states, there's a chance that we can reach ::Active
    3677            0 :                     self.activate_now();
    3678            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3679            0 :                         Ok(r) => {
    3680            0 :                             r.map_err(
    3681            0 :                             |_e: tokio::sync::watch::error::RecvError|
    3682              :                                 // Tenant existed but was dropped: report it as non-existent
    3683            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3684            0 :                         )?
    3685              :                         }
    3686              :                         Err(TimeoutCancellableError::Cancelled) => {
    3687            0 :                             return Err(GetActiveTenantError::Cancelled);
    3688              :                         }
    3689              :                         Err(TimeoutCancellableError::Timeout) => {
    3690            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3691            0 :                                 latest_state: Some(self.current_state()),
    3692            0 :                                 wait_time: timeout,
    3693            0 :                             });
    3694              :                         }
    3695              :                     }
    3696              :                 }
    3697              :                 TenantState::Active => {
    3698            0 :                     return Ok(());
    3699              :                 }
    3700            0 :                 TenantState::Broken { reason, .. } => {
    3701            0 :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3702            0 :                     // it's logically a 500 to external API users (broken is always a bug).
    3703            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3704              :                 }
    3705              :                 TenantState::Stopping { .. } => {
    3706              :                     // There's no chance the tenant can transition back into ::Active
    3707            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3708              :                 }
    3709              :             }
    3710              :         }
    3711            0 :     }
    3712              : 
    3713            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3714            0 :         self.tenant_conf.load().location.attach_mode
    3715            0 :     }
    3716              : 
    3717              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3718              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3719              :     /// rare external API calls, like a reconciliation at startup.
    3720            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3721            0 :         let attached_tenant_conf = self.tenant_conf.load();
    3722              : 
    3723            0 :         let location_config_mode = match attached_tenant_conf.location.attach_mode {
    3724            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3725            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3726            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3727              :         };
    3728              : 
    3729            0 :         models::LocationConfig {
    3730            0 :             mode: location_config_mode,
    3731            0 :             generation: self.generation.into(),
    3732            0 :             secondary_conf: None,
    3733            0 :             shard_number: self.shard_identity.number.0,
    3734            0 :             shard_count: self.shard_identity.count.literal(),
    3735            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3736            0 :             tenant_conf: attached_tenant_conf.tenant_conf.clone(),
    3737            0 :         }
    3738            0 :     }
    3739              : 
    3740            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3741            0 :         &self.tenant_shard_id
    3742            0 :     }
    3743              : 
    3744         1416 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3745         1416 :         self.shard_identity.stripe_size
    3746         1416 :     }
    3747              : 
    3748            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3749            0 :         self.generation
    3750            0 :     }
    3751              : 
    3752              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3753              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3754              :     /// resetting this tenant to a valid state if we fail.
    3755            0 :     pub(crate) async fn split_prepare(
    3756            0 :         &self,
    3757            0 :         child_shards: &Vec<TenantShardId>,
    3758            0 :     ) -> anyhow::Result<()> {
    3759            0 :         let (timelines, offloaded) = {
    3760            0 :             let timelines = self.timelines.lock().unwrap();
    3761            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3762            0 :             (timelines.clone(), offloaded.clone())
    3763            0 :         };
    3764            0 :         let timelines_iter = timelines
    3765            0 :             .values()
    3766            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3767            0 :             .chain(
    3768            0 :                 offloaded
    3769            0 :                     .values()
    3770            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3771            0 :             );
    3772            0 :         for timeline in timelines_iter {
    3773              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3774              :             // to ensure that they do not start a split if currently in the process of doing these.
    3775              : 
    3776            0 :             let timeline_id = timeline.timeline_id();
    3777              : 
    3778            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3779              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3780              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3781              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3782            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3783            0 :                 timeline
    3784            0 :                     .remote_client
    3785            0 :                     .schedule_index_upload_for_file_changes()?;
    3786            0 :                 timeline.remote_client.wait_completion().await?;
    3787            0 :             }
    3788              : 
    3789            0 :             let remote_client = match timeline {
    3790            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3791            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3792            0 :                     let remote_client = self
    3793            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3794            0 :                     Arc::new(remote_client)
    3795              :                 }
    3796              :             };
    3797              : 
    3798              :             // Shut down the timeline's remote client: this means that the indices we write
    3799              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3800            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3801            0 :             remote_client.shutdown().await;
    3802              : 
    3803              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3804              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3805              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3806              :             // we use here really is the remotely persistent one).
    3807            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3808            0 :             let result = remote_client
    3809            0 :                 .download_index_file(&self.cancel)
    3810            0 :                 .instrument(info_span!("download_index_file", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))
    3811            0 :                 .await?;
    3812            0 :             let index_part = match result {
    3813              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3814            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3815              :                 }
    3816            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3817              :             };
    3818              : 
    3819              :             // A shard split may not take place while a timeline import is on-going
    3820              :             // for the tenant. Timeline imports run as part of each tenant shard
    3821              :             // and rely on the sharding scheme to split the work among pageservers.
    3822              :             // If we were to split in the middle of this process, we would have to
    3823              :             // either ensure that it's driven to completion on the old shard set
    3824              :             // or transfer it to the new shard set. It's technically possible, but complex.
    3825            0 :             match index_part.import_pgdata {
    3826            0 :                 Some(ref import) if !import.is_done() => {
    3827            0 :                     anyhow::bail!(
    3828            0 :                         "Cannot split due to import with idempotency key: {:?}",
    3829            0 :                         import.idempotency_key()
    3830            0 :                     );
    3831              :                 }
    3832            0 :                 Some(_) | None => {
    3833            0 :                     // fallthrough
    3834            0 :                 }
    3835              :             }
    3836              : 
    3837            0 :             for child_shard in child_shards {
    3838            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3839            0 :                 upload_index_part(
    3840            0 :                     &self.remote_storage,
    3841            0 :                     child_shard,
    3842            0 :                     &timeline_id,
    3843            0 :                     self.generation,
    3844            0 :                     &index_part,
    3845            0 :                     &self.cancel,
    3846            0 :                 )
    3847            0 :                 .await?;
    3848              :             }
    3849              :         }
    3850              : 
    3851            0 :         let tenant_manifest = self.build_tenant_manifest();
    3852            0 :         for child_shard in child_shards {
    3853            0 :             tracing::info!(
    3854            0 :                 "Uploading tenant manifest for child {}",
    3855            0 :                 child_shard.to_index()
    3856              :             );
    3857            0 :             upload_tenant_manifest(
    3858            0 :                 &self.remote_storage,
    3859            0 :                 child_shard,
    3860            0 :                 self.generation,
    3861            0 :                 &tenant_manifest,
    3862            0 :                 &self.cancel,
    3863            0 :             )
    3864            0 :             .await?;
    3865              :         }
    3866              : 
    3867            0 :         Ok(())
    3868            0 :     }
    3869              : 
    3870            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    3871            0 :         let mut result = TopTenantShardItem {
    3872            0 :             id: self.tenant_shard_id,
    3873            0 :             resident_size: 0,
    3874            0 :             physical_size: 0,
    3875            0 :             max_logical_size: 0,
    3876            0 :             max_logical_size_per_shard: 0,
    3877            0 :         };
    3878              : 
    3879            0 :         for timeline in self.timelines.lock().unwrap().values() {
    3880            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    3881            0 : 
    3882            0 :             result.physical_size += timeline
    3883            0 :                 .remote_client
    3884            0 :                 .metrics
    3885            0 :                 .remote_physical_size_gauge
    3886            0 :                 .get();
    3887            0 :             result.max_logical_size = std::cmp::max(
    3888            0 :                 result.max_logical_size,
    3889            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    3890            0 :             );
    3891            0 :         }
    3892              : 
    3893            0 :         result.max_logical_size_per_shard = result
    3894            0 :             .max_logical_size
    3895            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    3896            0 : 
    3897            0 :         result
    3898            0 :     }
    3899              : }
    3900              : 
    3901              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    3902              : /// perform a topological sort, so that the parent of each timeline comes
    3903              : /// before the children.
    3904              : /// E extracts the ancestor from T
    3905              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    3906         1404 : fn tree_sort_timelines<T, E>(
    3907         1404 :     timelines: HashMap<TimelineId, T>,
    3908         1404 :     extractor: E,
    3909         1404 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    3910         1404 : where
    3911         1404 :     E: Fn(&T) -> Option<TimelineId>,
    3912         1404 : {
    3913         1404 :     let mut result = Vec::with_capacity(timelines.len());
    3914         1404 : 
    3915         1404 :     let mut now = Vec::with_capacity(timelines.len());
    3916         1404 :     // (ancestor, children)
    3917         1404 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    3918         1404 :         HashMap::with_capacity(timelines.len());
    3919              : 
    3920         1440 :     for (timeline_id, value) in timelines {
    3921           36 :         if let Some(ancestor_id) = extractor(&value) {
    3922           12 :             let children = later.entry(ancestor_id).or_default();
    3923           12 :             children.push((timeline_id, value));
    3924           24 :         } else {
    3925           24 :             now.push((timeline_id, value));
    3926           24 :         }
    3927              :     }
    3928              : 
    3929         1440 :     while let Some((timeline_id, metadata)) = now.pop() {
    3930           36 :         result.push((timeline_id, metadata));
    3931              :         // All children of this can be loaded now
    3932           36 :         if let Some(mut children) = later.remove(&timeline_id) {
    3933           12 :             now.append(&mut children);
    3934           24 :         }
    3935              :     }
    3936              : 
    3937              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    3938         1404 :     if !later.is_empty() {
    3939            0 :         for (missing_id, orphan_ids) in later {
    3940            0 :             for (orphan_id, _) in orphan_ids {
    3941            0 :                 error!(
    3942            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    3943              :                 );
    3944              :             }
    3945              :         }
    3946            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    3947         1404 :     }
    3948         1404 : 
    3949         1404 :     Ok(result)
    3950         1404 : }
    3951              : 
    3952              : enum ActivateTimelineArgs {
    3953              :     Yes {
    3954              :         broker_client: storage_broker::BrokerClientChannel,
    3955              :     },
    3956              :     No,
    3957              : }
    3958              : 
    3959              : impl TenantShard {
    3960            0 :     pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
    3961            0 :         self.tenant_conf.load().tenant_conf.clone()
    3962            0 :     }
    3963              : 
    3964            0 :     pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
    3965            0 :         self.tenant_specific_overrides()
    3966            0 :             .merge(self.conf.default_tenant_conf.clone())
    3967            0 :     }
    3968              : 
    3969            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    3970            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3971            0 :         tenant_conf
    3972            0 :             .checkpoint_distance
    3973            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    3974            0 :     }
    3975              : 
    3976            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    3977            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3978            0 :         tenant_conf
    3979            0 :             .checkpoint_timeout
    3980            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    3981            0 :     }
    3982              : 
    3983            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    3984            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3985            0 :         tenant_conf
    3986            0 :             .compaction_target_size
    3987            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    3988            0 :     }
    3989              : 
    3990            0 :     pub fn get_compaction_period(&self) -> Duration {
    3991            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3992            0 :         tenant_conf
    3993            0 :             .compaction_period
    3994            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    3995            0 :     }
    3996              : 
    3997            0 :     pub fn get_compaction_threshold(&self) -> usize {
    3998            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    3999            0 :         tenant_conf
    4000            0 :             .compaction_threshold
    4001            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    4002            0 :     }
    4003              : 
    4004            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    4005            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4006            0 :         tenant_conf
    4007            0 :             .rel_size_v2_enabled
    4008            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    4009            0 :     }
    4010              : 
    4011            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    4012            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4013            0 :         tenant_conf
    4014            0 :             .compaction_upper_limit
    4015            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    4016            0 :     }
    4017              : 
    4018            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    4019            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4020            0 :         tenant_conf
    4021            0 :             .compaction_l0_first
    4022            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    4023            0 :     }
    4024              : 
    4025           24 :     pub fn get_gc_horizon(&self) -> u64 {
    4026           24 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4027           24 :         tenant_conf
    4028           24 :             .gc_horizon
    4029           24 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4030           24 :     }
    4031              : 
    4032            0 :     pub fn get_gc_period(&self) -> Duration {
    4033            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4034            0 :         tenant_conf
    4035            0 :             .gc_period
    4036            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4037            0 :     }
    4038              : 
    4039            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4040            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4041            0 :         tenant_conf
    4042            0 :             .image_creation_threshold
    4043            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4044            0 :     }
    4045              : 
    4046           24 :     pub fn get_pitr_interval(&self) -> Duration {
    4047           24 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4048           24 :         tenant_conf
    4049           24 :             .pitr_interval
    4050           24 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4051           24 :     }
    4052              : 
    4053            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4054            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4055            0 :         tenant_conf
    4056            0 :             .min_resident_size_override
    4057            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4058            0 :     }
    4059              : 
    4060            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4061            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4062            0 :         let heatmap_period = tenant_conf
    4063            0 :             .heatmap_period
    4064            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4065            0 :         if heatmap_period.is_zero() {
    4066            0 :             None
    4067              :         } else {
    4068            0 :             Some(heatmap_period)
    4069              :         }
    4070            0 :     }
    4071              : 
    4072           24 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4073           24 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4074           24 :         tenant_conf
    4075           24 :             .lsn_lease_length
    4076           24 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4077           24 :     }
    4078              : 
    4079            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4080            0 :         if self.conf.timeline_offloading {
    4081            0 :             return true;
    4082            0 :         }
    4083            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4084            0 :         tenant_conf
    4085            0 :             .timeline_offloading
    4086            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4087            0 :     }
    4088              : 
    4089              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4090         1416 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4091         1416 :         // Collect the offloaded timelines, and sort them for deterministic output.
    4092         1416 :         let offloaded_timelines = self
    4093         1416 :             .timelines_offloaded
    4094         1416 :             .lock()
    4095         1416 :             .unwrap()
    4096         1416 :             .values()
    4097         1416 :             .map(|tli| tli.manifest())
    4098         1416 :             .sorted_by_key(|m| m.timeline_id)
    4099         1416 :             .collect_vec();
    4100         1416 : 
    4101         1416 :         TenantManifest {
    4102         1416 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4103         1416 :             stripe_size: Some(self.get_shard_stripe_size()),
    4104         1416 :             offloaded_timelines,
    4105         1416 :         }
    4106         1416 :     }
    4107              : 
    4108            0 :     pub fn update_tenant_config<
    4109            0 :         F: Fn(
    4110            0 :             pageserver_api::models::TenantConfig,
    4111            0 :         ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
    4112            0 :     >(
    4113            0 :         &self,
    4114            0 :         update: F,
    4115            0 :     ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
    4116            0 :         // Use read-copy-update in order to avoid overwriting the location config
    4117            0 :         // state if this races with [`TenantShard::set_new_location_config`]. Note that
    4118            0 :         // this race is not possible if both request types come from the storage
    4119            0 :         // controller (as they should!) because an exclusive op lock is required
    4120            0 :         // on the storage controller side.
    4121            0 : 
    4122            0 :         self.tenant_conf
    4123            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4124            0 :                 Ok(Arc::new(AttachedTenantConf {
    4125            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4126            0 :                     location: attached_conf.location,
    4127            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4128              :                 }))
    4129            0 :             })?;
    4130              : 
    4131            0 :         let updated = self.tenant_conf.load();
    4132            0 : 
    4133            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    4134            0 :         // Don't hold self.timelines.lock() during the notifies.
    4135            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4136            0 :         // mutexes in struct Timeline in the future.
    4137            0 :         let timelines = self.list_timelines();
    4138            0 :         for timeline in timelines {
    4139            0 :             timeline.tenant_conf_updated(&updated);
    4140            0 :         }
    4141              : 
    4142            0 :         Ok(updated.tenant_conf.clone())
    4143            0 :     }
    4144              : 
    4145            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4146            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4147            0 : 
    4148            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4149            0 : 
    4150            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4151            0 :         // Don't hold self.timelines.lock() during the notifies.
    4152            0 :         // There's no risk of deadlock right now, but there could be if we consolidate
    4153            0 :         // mutexes in struct Timeline in the future.
    4154            0 :         let timelines = self.list_timelines();
    4155            0 :         for timeline in timelines {
    4156            0 :             timeline.tenant_conf_updated(&new_conf);
    4157            0 :         }
    4158            0 :     }
    4159              : 
    4160         1404 :     fn get_pagestream_throttle_config(
    4161         1404 :         psconf: &'static PageServerConf,
    4162         1404 :         overrides: &pageserver_api::models::TenantConfig,
    4163         1404 :     ) -> throttle::Config {
    4164         1404 :         overrides
    4165         1404 :             .timeline_get_throttle
    4166         1404 :             .clone()
    4167         1404 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4168         1404 :     }
    4169              : 
    4170            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
    4171            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4172            0 :         self.pagestream_throttle.reconfigure(conf)
    4173            0 :     }
    4174              : 
    4175              :     /// Helper function to create a new Timeline struct.
    4176              :     ///
    4177              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4178              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4179              :     /// map.
    4180              :     ///
    4181              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4182              :     /// and we might not have the ancestor present anymore which is fine for to be
    4183              :     /// deleted timelines.
    4184              :     #[allow(clippy::too_many_arguments)]
    4185         2796 :     fn create_timeline_struct(
    4186         2796 :         &self,
    4187         2796 :         new_timeline_id: TimelineId,
    4188         2796 :         new_metadata: &TimelineMetadata,
    4189         2796 :         previous_heatmap: Option<PreviousHeatmap>,
    4190         2796 :         ancestor: Option<Arc<Timeline>>,
    4191         2796 :         resources: TimelineResources,
    4192         2796 :         cause: CreateTimelineCause,
    4193         2796 :         create_idempotency: CreateTimelineIdempotency,
    4194         2796 :         gc_compaction_state: Option<GcCompactionState>,
    4195         2796 :         rel_size_v2_status: Option<RelSizeMigration>,
    4196         2796 :         ctx: &RequestContext,
    4197         2796 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4198         2796 :         let state = match cause {
    4199              :             CreateTimelineCause::Load => {
    4200         2796 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4201         2796 :                 anyhow::ensure!(
    4202         2796 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4203            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4204              :                 );
    4205         2796 :                 TimelineState::Loading
    4206              :             }
    4207            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4208              :         };
    4209              : 
    4210         2796 :         let pg_version = new_metadata.pg_version();
    4211         2796 : 
    4212         2796 :         let timeline = Timeline::new(
    4213         2796 :             self.conf,
    4214         2796 :             Arc::clone(&self.tenant_conf),
    4215         2796 :             new_metadata,
    4216         2796 :             previous_heatmap,
    4217         2796 :             ancestor,
    4218         2796 :             new_timeline_id,
    4219         2796 :             self.tenant_shard_id,
    4220         2796 :             self.generation,
    4221         2796 :             self.shard_identity,
    4222         2796 :             self.walredo_mgr.clone(),
    4223         2796 :             resources,
    4224         2796 :             pg_version,
    4225         2796 :             state,
    4226         2796 :             self.attach_wal_lag_cooldown.clone(),
    4227         2796 :             create_idempotency,
    4228         2796 :             gc_compaction_state,
    4229         2796 :             rel_size_v2_status,
    4230         2796 :             self.cancel.child_token(),
    4231         2796 :         );
    4232         2796 : 
    4233         2796 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4234         2796 :             .scope(context::Scope::new_timeline(&timeline))
    4235         2796 :             .detached_child();
    4236         2796 : 
    4237         2796 :         Ok((timeline, timeline_ctx))
    4238         2796 :     }
    4239              : 
    4240              :     /// [`TenantShard::shutdown`] must be called before dropping the returned [`TenantShard`] object
    4241              :     /// to ensure proper cleanup of background tasks and metrics.
    4242              :     //
    4243              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4244              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4245              :     #[allow(clippy::too_many_arguments)]
    4246         1404 :     fn new(
    4247         1404 :         state: TenantState,
    4248         1404 :         conf: &'static PageServerConf,
    4249         1404 :         attached_conf: AttachedTenantConf,
    4250         1404 :         shard_identity: ShardIdentity,
    4251         1404 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4252         1404 :         tenant_shard_id: TenantShardId,
    4253         1404 :         remote_storage: GenericRemoteStorage,
    4254         1404 :         deletion_queue_client: DeletionQueueClient,
    4255         1404 :         l0_flush_global_state: L0FlushGlobalState,
    4256         1404 :     ) -> TenantShard {
    4257         1404 :         assert!(!attached_conf.location.generation.is_none());
    4258              : 
    4259         1404 :         let (state, mut rx) = watch::channel(state);
    4260         1404 : 
    4261         1404 :         tokio::spawn(async move {
    4262         1402 :             // reflect tenant state in metrics:
    4263         1402 :             // - global per tenant state: TENANT_STATE_METRIC
    4264         1402 :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4265         1402 :             //
    4266         1402 :             // set of broken tenants should not have zero counts so that it remains accessible for
    4267         1402 :             // alerting.
    4268         1402 : 
    4269         1402 :             let tid = tenant_shard_id.to_string();
    4270         1402 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4271         1402 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4272              : 
    4273         2798 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4274         2798 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4275         2798 :             }
    4276              : 
    4277         1402 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4278         1402 : 
    4279         1402 :             let is_broken = tuple.1;
    4280         1402 :             let mut counted_broken = if is_broken {
    4281              :                 // add the id to the set right away, there should not be any updates on the channel
    4282              :                 // after before tenant is removed, if ever
    4283            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4284            0 :                 true
    4285              :             } else {
    4286         1402 :                 false
    4287              :             };
    4288              : 
    4289              :             loop {
    4290         2798 :                 let labels = &tuple.0;
    4291         2798 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4292         2798 :                 current.inc();
    4293         2798 : 
    4294         2798 :                 if rx.changed().await.is_err() {
    4295              :                     // tenant has been dropped
    4296           84 :                     current.dec();
    4297           84 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4298           84 :                     break;
    4299         1396 :                 }
    4300         1396 : 
    4301         1396 :                 current.dec();
    4302         1396 :                 tuple = inspect_state(&rx.borrow_and_update());
    4303         1396 : 
    4304         1396 :                 let is_broken = tuple.1;
    4305         1396 :                 if is_broken && !counted_broken {
    4306            0 :                     counted_broken = true;
    4307            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4308            0 :                     // access
    4309            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4310         1396 :                 }
    4311              :             }
    4312         1404 :         });
    4313         1404 : 
    4314         1404 :         TenantShard {
    4315         1404 :             tenant_shard_id,
    4316         1404 :             shard_identity,
    4317         1404 :             generation: attached_conf.location.generation,
    4318         1404 :             conf,
    4319         1404 :             // using now here is good enough approximation to catch tenants with really long
    4320         1404 :             // activation times.
    4321         1404 :             constructed_at: Instant::now(),
    4322         1404 :             timelines: Mutex::new(HashMap::new()),
    4323         1404 :             timelines_creating: Mutex::new(HashSet::new()),
    4324         1404 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4325         1404 :             remote_tenant_manifest: Default::default(),
    4326         1404 :             gc_cs: tokio::sync::Mutex::new(()),
    4327         1404 :             walredo_mgr,
    4328         1404 :             remote_storage,
    4329         1404 :             deletion_queue_client,
    4330         1404 :             state,
    4331         1404 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4332         1404 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4333         1404 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4334         1404 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4335         1404 :                 format!("compaction-{tenant_shard_id}"),
    4336         1404 :                 5,
    4337         1404 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4338         1404 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4339         1404 :                 // use an extremely long backoff.
    4340         1404 :                 Some(Duration::from_secs(3600 * 24)),
    4341         1404 :             )),
    4342         1404 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4343         1404 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4344         1404 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4345         1404 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4346         1404 :             cancel: CancellationToken::default(),
    4347         1404 :             gate: Gate::default(),
    4348         1404 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4349         1404 :                 TenantShard::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4350         1404 :             )),
    4351         1404 :             pagestream_throttle_metrics: Arc::new(
    4352         1404 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4353         1404 :             ),
    4354         1404 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4355         1404 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4356         1404 :             gc_block: Default::default(),
    4357         1404 :             l0_flush_global_state,
    4358         1404 :         }
    4359         1404 :     }
    4360              : 
    4361              :     /// Locate and load config
    4362            0 :     pub(super) fn load_tenant_config(
    4363            0 :         conf: &'static PageServerConf,
    4364            0 :         tenant_shard_id: &TenantShardId,
    4365            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4366            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4367            0 : 
    4368            0 :         info!("loading tenant configuration from {config_path}");
    4369              : 
    4370              :         // load and parse file
    4371            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4372            0 :             match e.kind() {
    4373              :                 std::io::ErrorKind::NotFound => {
    4374              :                     // The config should almost always exist for a tenant directory:
    4375              :                     //  - When attaching a tenant, the config is the first thing we write
    4376              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4377              :                     //    before deleting contents.
    4378              :                     //
    4379              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4380              :                     // between creating directory and writing config.  Callers should handle that as if the
    4381              :                     // directory didn't exist.
    4382              : 
    4383            0 :                     LoadConfigError::NotFound(config_path)
    4384              :                 }
    4385              :                 _ => {
    4386              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4387              :                     // that we cannot cleanly recover
    4388            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4389              :                 }
    4390              :             }
    4391            0 :         })?;
    4392              : 
    4393            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4394            0 :     }
    4395              : 
    4396              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4397              :     pub(super) async fn persist_tenant_config(
    4398              :         conf: &'static PageServerConf,
    4399              :         tenant_shard_id: &TenantShardId,
    4400              :         location_conf: &LocationConf,
    4401              :     ) -> std::io::Result<()> {
    4402              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4403              : 
    4404              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4405              :     }
    4406              : 
    4407              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4408              :     pub(super) async fn persist_tenant_config_at(
    4409              :         tenant_shard_id: &TenantShardId,
    4410              :         config_path: &Utf8Path,
    4411              :         location_conf: &LocationConf,
    4412              :     ) -> std::io::Result<()> {
    4413              :         debug!("persisting tenantconf to {config_path}");
    4414              : 
    4415              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4416              : #  It is read in case of pageserver restart.
    4417              : "#
    4418              :         .to_string();
    4419              : 
    4420            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4421            0 :             Err(std::io::Error::other("tenant-config-before-write"))
    4422            0 :         });
    4423              : 
    4424              :         // Convert the config to a toml file.
    4425              :         conf_content +=
    4426              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4427              : 
    4428              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4429              : 
    4430              :         let conf_content = conf_content.into_bytes();
    4431              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4432              :     }
    4433              : 
    4434              :     //
    4435              :     // How garbage collection works:
    4436              :     //
    4437              :     //                    +--bar------------->
    4438              :     //                   /
    4439              :     //             +----+-----foo---------------->
    4440              :     //            /
    4441              :     // ----main--+-------------------------->
    4442              :     //                \
    4443              :     //                 +-----baz-------->
    4444              :     //
    4445              :     //
    4446              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4447              :     //    `gc_infos` are being refreshed
    4448              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4449              :     //    all the points where other timelines have been branched off.
    4450              :     //    We will refrain from removing page versions at those LSNs.
    4451              :     // 3. For each timeline, scan all layer files on the timeline.
    4452              :     //    Remove all files for which a newer file exists and which
    4453              :     //    don't cover any branch point LSNs.
    4454              :     //
    4455              :     // TODO:
    4456              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4457              :     //   don't need to keep that in the parent anymore. But currently
    4458              :     //   we do.
    4459           24 :     async fn gc_iteration_internal(
    4460           24 :         &self,
    4461           24 :         target_timeline_id: Option<TimelineId>,
    4462           24 :         horizon: u64,
    4463           24 :         pitr: Duration,
    4464           24 :         cancel: &CancellationToken,
    4465           24 :         ctx: &RequestContext,
    4466           24 :     ) -> Result<GcResult, GcError> {
    4467           24 :         let mut totals: GcResult = Default::default();
    4468           24 :         let now = Instant::now();
    4469              : 
    4470           24 :         let gc_timelines = self
    4471           24 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4472           24 :             .await?;
    4473              : 
    4474           24 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4475              : 
    4476              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4477           24 :         if !gc_timelines.is_empty() {
    4478           24 :             info!("{} timelines need GC", gc_timelines.len());
    4479              :         } else {
    4480            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4481              :         }
    4482              : 
    4483              :         // Perform GC for each timeline.
    4484              :         //
    4485              :         // Note that we don't hold the `TenantShard::gc_cs` lock here because we don't want to delay the
    4486              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4487              :         // with branch creation.
    4488              :         //
    4489              :         // See comments in [`TenantShard::branch_timeline`] for more information about why branch
    4490              :         // creation task can run concurrently with timeline's GC iteration.
    4491           48 :         for timeline in gc_timelines {
    4492           24 :             if cancel.is_cancelled() {
    4493              :                 // We were requested to shut down. Stop and return with the progress we
    4494              :                 // made.
    4495            0 :                 break;
    4496           24 :             }
    4497           24 :             let result = match timeline.gc().await {
    4498              :                 Err(GcError::TimelineCancelled) => {
    4499            0 :                     if target_timeline_id.is_some() {
    4500              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4501            0 :                         return Err(GcError::TimelineCancelled);
    4502              :                     } else {
    4503              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4504              :                         // skip past this and proceed to try GC on other timelines.
    4505            0 :                         continue;
    4506              :                     }
    4507              :                 }
    4508           24 :                 r => r?,
    4509              :             };
    4510           24 :             totals += result;
    4511              :         }
    4512              : 
    4513           24 :         totals.elapsed = now.elapsed();
    4514           24 :         Ok(totals)
    4515           24 :     }
    4516              : 
    4517              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4518              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4519              :     /// [`TenantShard::get_gc_horizon`].
    4520              :     ///
    4521              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4522           24 :     pub(crate) async fn refresh_gc_info(
    4523           24 :         &self,
    4524           24 :         cancel: &CancellationToken,
    4525           24 :         ctx: &RequestContext,
    4526           24 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4527           24 :         // since this method can now be called at different rates than the configured gc loop, it
    4528           24 :         // might be that these configuration values get applied faster than what it was previously,
    4529           24 :         // since these were only read from the gc task.
    4530           24 :         let horizon = self.get_gc_horizon();
    4531           24 :         let pitr = self.get_pitr_interval();
    4532           24 : 
    4533           24 :         // refresh all timelines
    4534           24 :         let target_timeline_id = None;
    4535           24 : 
    4536           24 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4537           24 :             .await
    4538           24 :     }
    4539              : 
    4540              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4541              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4542              :     ///
    4543              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4544            0 :     fn initialize_gc_info(
    4545            0 :         &self,
    4546            0 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4547            0 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4548            0 :         restrict_to_timeline: Option<TimelineId>,
    4549            0 :     ) {
    4550            0 :         if restrict_to_timeline.is_none() {
    4551              :             // This function must be called before activation: after activation timeline create/delete operations
    4552              :             // might happen, and this function is not safe to run concurrently with those.
    4553            0 :             assert!(!self.is_active());
    4554            0 :         }
    4555              : 
    4556              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4557              :         // the branch point where it was created.
    4558            0 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4559            0 :             BTreeMap::new();
    4560            0 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4561            0 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4562            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4563            0 :                 ancestor_children.push((
    4564            0 :                     timeline_entry.get_ancestor_lsn(),
    4565            0 :                     *timeline_id,
    4566            0 :                     MaybeOffloaded::No,
    4567            0 :                 ));
    4568            0 :             }
    4569            0 :         });
    4570            0 :         timelines_offloaded
    4571            0 :             .iter()
    4572            0 :             .for_each(|(timeline_id, timeline_entry)| {
    4573            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4574            0 :                     return;
    4575              :                 };
    4576            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4577            0 :                     return;
    4578              :                 };
    4579            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4580            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4581            0 :             });
    4582            0 : 
    4583            0 :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4584            0 :         let horizon = self.get_gc_horizon();
    4585              : 
    4586              :         // Populate each timeline's GcInfo with information about its child branches
    4587            0 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4588            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4589              :         } else {
    4590            0 :             itertools::Either::Right(timelines.values())
    4591              :         };
    4592            0 :         for timeline in timelines_to_write {
    4593            0 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4594            0 :                 .remove(&timeline.timeline_id)
    4595            0 :                 .unwrap_or_default();
    4596            0 : 
    4597            0 :             branchpoints.sort_by_key(|b| b.0);
    4598            0 : 
    4599            0 :             let mut target = timeline.gc_info.write().unwrap();
    4600            0 : 
    4601            0 :             target.retain_lsns = branchpoints;
    4602            0 : 
    4603            0 :             let space_cutoff = timeline
    4604            0 :                 .get_last_record_lsn()
    4605            0 :                 .checked_sub(horizon)
    4606            0 :                 .unwrap_or(Lsn(0));
    4607            0 : 
    4608            0 :             target.cutoffs = GcCutoffs {
    4609            0 :                 space: space_cutoff,
    4610            0 :                 time: Lsn::INVALID,
    4611            0 :             };
    4612            0 :         }
    4613            0 :     }
    4614              : 
    4615           48 :     async fn refresh_gc_info_internal(
    4616           48 :         &self,
    4617           48 :         target_timeline_id: Option<TimelineId>,
    4618           48 :         horizon: u64,
    4619           48 :         pitr: Duration,
    4620           48 :         cancel: &CancellationToken,
    4621           48 :         ctx: &RequestContext,
    4622           48 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4623           48 :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4624           48 :         // currently visible timelines.
    4625           48 :         let timelines = self
    4626           48 :             .timelines
    4627           48 :             .lock()
    4628           48 :             .unwrap()
    4629           48 :             .values()
    4630          120 :             .filter(|tl| match target_timeline_id.as_ref() {
    4631           24 :                 Some(target) => &tl.timeline_id == target,
    4632           96 :                 None => true,
    4633          120 :             })
    4634           48 :             .cloned()
    4635           48 :             .collect::<Vec<_>>();
    4636           48 : 
    4637           48 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4638              :             // We were to act on a particular timeline and it wasn't found
    4639            0 :             return Err(GcError::TimelineNotFound);
    4640           48 :         }
    4641           48 : 
    4642           48 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4643           48 :             HashMap::with_capacity(timelines.len());
    4644           48 : 
    4645           48 :         // Ensures all timelines use the same start time when computing the time cutoff.
    4646           48 :         let now_ts_for_pitr_calc = SystemTime::now();
    4647          120 :         for timeline in timelines.iter() {
    4648          120 :             let ctx = &ctx.with_scope_timeline(timeline);
    4649          120 :             let cutoff = timeline
    4650          120 :                 .get_last_record_lsn()
    4651          120 :                 .checked_sub(horizon)
    4652          120 :                 .unwrap_or(Lsn(0));
    4653              : 
    4654          120 :             let cutoffs = timeline
    4655          120 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4656          120 :                 .await?;
    4657          120 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4658          120 :             assert!(old.is_none());
    4659              :         }
    4660              : 
    4661           48 :         if !self.is_active() || self.cancel.is_cancelled() {
    4662            0 :             return Err(GcError::TenantCancelled);
    4663           48 :         }
    4664              : 
    4665              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4666              :         // because that will stall branch creation.
    4667           48 :         let gc_cs = self.gc_cs.lock().await;
    4668              : 
    4669              :         // Ok, we now know all the branch points.
    4670              :         // Update the GC information for each timeline.
    4671           48 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4672          168 :         for timeline in timelines {
    4673              :             // We filtered the timeline list above
    4674          120 :             if let Some(target_timeline_id) = target_timeline_id {
    4675           24 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4676           96 :             }
    4677              : 
    4678              :             {
    4679          120 :                 let mut target = timeline.gc_info.write().unwrap();
    4680          120 : 
    4681          120 :                 // Cull any expired leases
    4682          120 :                 let now = SystemTime::now();
    4683          120 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4684          120 : 
    4685          120 :                 timeline
    4686          120 :                     .metrics
    4687          120 :                     .valid_lsn_lease_count_gauge
    4688          120 :                     .set(target.leases.len() as u64);
    4689              : 
    4690              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4691          120 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4692           72 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4693           72 :                         target.within_ancestor_pitr =
    4694           72 :                             timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
    4695           72 :                     }
    4696           48 :                 }
    4697              : 
    4698              :                 // Update metrics that depend on GC state
    4699          120 :                 timeline
    4700          120 :                     .metrics
    4701          120 :                     .archival_size
    4702          120 :                     .set(if target.within_ancestor_pitr {
    4703            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4704              :                     } else {
    4705          120 :                         0
    4706              :                     });
    4707          120 :                 timeline.metrics.pitr_history_size.set(
    4708          120 :                     timeline
    4709          120 :                         .get_last_record_lsn()
    4710          120 :                         .checked_sub(target.cutoffs.time)
    4711          120 :                         .unwrap_or(Lsn(0))
    4712          120 :                         .0,
    4713          120 :                 );
    4714              : 
    4715              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4716              :                 // - this timeline was created while we were finding cutoffs
    4717              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4718          120 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4719          120 :                     let original_cutoffs = target.cutoffs.clone();
    4720          120 :                     // GC cutoffs should never go back
    4721          120 :                     target.cutoffs = GcCutoffs {
    4722          120 :                         space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
    4723          120 :                         time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
    4724          120 :                     }
    4725            0 :                 }
    4726              :             }
    4727              : 
    4728          120 :             gc_timelines.push(timeline);
    4729              :         }
    4730           48 :         drop(gc_cs);
    4731           48 :         Ok(gc_timelines)
    4732           48 :     }
    4733              : 
    4734              :     /// A substitute for `branch_timeline` for use in unit tests.
    4735              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4736              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4737              :     /// timeline background tasks are launched, except the flush loop.
    4738              :     #[cfg(test)]
    4739         1428 :     async fn branch_timeline_test(
    4740         1428 :         self: &Arc<Self>,
    4741         1428 :         src_timeline: &Arc<Timeline>,
    4742         1428 :         dst_id: TimelineId,
    4743         1428 :         ancestor_lsn: Option<Lsn>,
    4744         1428 :         ctx: &RequestContext,
    4745         1428 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4746         1428 :         let tl = self
    4747         1428 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4748         1428 :             .await?
    4749         1404 :             .into_timeline_for_test();
    4750         1404 :         tl.set_state(TimelineState::Active);
    4751         1404 :         Ok(tl)
    4752         1428 :     }
    4753              : 
    4754              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4755              :     #[cfg(test)]
    4756              :     #[allow(clippy::too_many_arguments)]
    4757           72 :     pub async fn branch_timeline_test_with_layers(
    4758           72 :         self: &Arc<Self>,
    4759           72 :         src_timeline: &Arc<Timeline>,
    4760           72 :         dst_id: TimelineId,
    4761           72 :         ancestor_lsn: Option<Lsn>,
    4762           72 :         ctx: &RequestContext,
    4763           72 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4764           72 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4765           72 :         end_lsn: Lsn,
    4766           72 :     ) -> anyhow::Result<Arc<Timeline>> {
    4767              :         use checks::check_valid_layermap;
    4768              :         use itertools::Itertools;
    4769              : 
    4770           72 :         let tline = self
    4771           72 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4772           72 :             .await?;
    4773           72 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4774           72 :             ancestor_lsn
    4775              :         } else {
    4776            0 :             tline.get_last_record_lsn()
    4777              :         };
    4778           72 :         assert!(end_lsn >= ancestor_lsn);
    4779           72 :         tline.force_advance_lsn(end_lsn);
    4780          108 :         for deltas in delta_layer_desc {
    4781           36 :             tline
    4782           36 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4783           36 :                 .await?;
    4784              :         }
    4785           96 :         for (lsn, images) in image_layer_desc {
    4786           24 :             tline
    4787           24 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4788           24 :                 .await?;
    4789              :         }
    4790           72 :         let layer_names = tline
    4791           72 :             .layers
    4792           72 :             .read()
    4793           72 :             .await
    4794           72 :             .layer_map()
    4795           72 :             .unwrap()
    4796           72 :             .iter_historic_layers()
    4797           72 :             .map(|layer| layer.layer_name())
    4798           72 :             .collect_vec();
    4799           72 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4800            0 :             bail!("invalid layermap: {err}");
    4801           72 :         }
    4802           72 :         Ok(tline)
    4803           72 :     }
    4804              : 
    4805              :     /// Branch an existing timeline.
    4806            0 :     async fn branch_timeline(
    4807            0 :         self: &Arc<Self>,
    4808            0 :         src_timeline: &Arc<Timeline>,
    4809            0 :         dst_id: TimelineId,
    4810            0 :         start_lsn: Option<Lsn>,
    4811            0 :         ctx: &RequestContext,
    4812            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4813            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4814            0 :             .await
    4815            0 :     }
    4816              : 
    4817         1428 :     async fn branch_timeline_impl(
    4818         1428 :         self: &Arc<Self>,
    4819         1428 :         src_timeline: &Arc<Timeline>,
    4820         1428 :         dst_id: TimelineId,
    4821         1428 :         start_lsn: Option<Lsn>,
    4822         1428 :         ctx: &RequestContext,
    4823         1428 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4824         1428 :         let src_id = src_timeline.timeline_id;
    4825              : 
    4826              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4827              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4828              :         // valid while we are creating the branch.
    4829         1428 :         let _gc_cs = self.gc_cs.lock().await;
    4830              : 
    4831              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4832         1428 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4833           12 :             let lsn = src_timeline.get_last_record_lsn();
    4834           12 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4835           12 :             lsn
    4836         1428 :         });
    4837              : 
    4838              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4839         1428 :         let timeline_create_guard = match self
    4840         1428 :             .start_creating_timeline(
    4841         1428 :                 dst_id,
    4842         1428 :                 CreateTimelineIdempotency::Branch {
    4843         1428 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4844         1428 :                     ancestor_start_lsn: start_lsn,
    4845         1428 :                 },
    4846         1428 :             )
    4847         1428 :             .await?
    4848              :         {
    4849         1428 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4850            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4851            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    4852              :             }
    4853              :         };
    4854              : 
    4855              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    4856              :         // horizon on the source timeline
    4857              :         //
    4858              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    4859              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    4860              :         // planned GC cutoff in 'gc_info' is normally larger than
    4861              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    4862              :         // changed the GC settings for the tenant to make the PITR window
    4863              :         // larger, but some of the data was already removed by an earlier GC
    4864              :         // iteration.
    4865              : 
    4866              :         // check against last actual 'latest_gc_cutoff' first
    4867         1428 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    4868         1428 :         {
    4869         1428 :             let gc_info = src_timeline.gc_info.read().unwrap();
    4870         1428 :             let planned_cutoff = gc_info.min_cutoff();
    4871         1428 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    4872            0 :                 tracing::info!(
    4873            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    4874            0 :                     *applied_gc_cutoff_lsn
    4875              :                 );
    4876              :             } else {
    4877         1428 :                 src_timeline
    4878         1428 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    4879         1428 :                     .context(format!(
    4880         1428 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    4881         1428 :                         *applied_gc_cutoff_lsn,
    4882         1428 :                     ))
    4883         1428 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    4884              : 
    4885              :                 // and then the planned GC cutoff
    4886         1404 :                 if start_lsn < planned_cutoff {
    4887            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    4888            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    4889            0 :                     )));
    4890         1404 :                 }
    4891              :             }
    4892              :         }
    4893              : 
    4894              :         //
    4895              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    4896              :         // so that GC cannot advance the GC cutoff until we are finished.
    4897              :         // Proceed with the branch creation.
    4898              :         //
    4899              : 
    4900              :         // Determine prev-LSN for the new timeline. We can only determine it if
    4901              :         // the timeline was branched at the current end of the source timeline.
    4902              :         let RecordLsn {
    4903         1404 :             last: src_last,
    4904         1404 :             prev: src_prev,
    4905         1404 :         } = src_timeline.get_last_record_rlsn();
    4906         1404 :         let dst_prev = if src_last == start_lsn {
    4907         1296 :             Some(src_prev)
    4908              :         } else {
    4909          108 :             None
    4910              :         };
    4911              : 
    4912              :         // Create the metadata file, noting the ancestor of the new timeline.
    4913              :         // There is initially no data in it, but all the read-calls know to look
    4914              :         // into the ancestor.
    4915         1404 :         let metadata = TimelineMetadata::new(
    4916         1404 :             start_lsn,
    4917         1404 :             dst_prev,
    4918         1404 :             Some(src_id),
    4919         1404 :             start_lsn,
    4920         1404 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    4921         1404 :             src_timeline.initdb_lsn,
    4922         1404 :             src_timeline.pg_version,
    4923         1404 :         );
    4924              : 
    4925         1404 :         let (uninitialized_timeline, _timeline_ctx) = self
    4926         1404 :             .prepare_new_timeline(
    4927         1404 :                 dst_id,
    4928         1404 :                 &metadata,
    4929         1404 :                 timeline_create_guard,
    4930         1404 :                 start_lsn + 1,
    4931         1404 :                 Some(Arc::clone(src_timeline)),
    4932         1404 :                 Some(src_timeline.get_rel_size_v2_status()),
    4933         1404 :                 ctx,
    4934         1404 :             )
    4935         1404 :             .await?;
    4936              : 
    4937         1404 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    4938              : 
    4939              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    4940              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    4941              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    4942              :         // could get incorrect information and remove more layers, than needed.
    4943              :         // See also https://github.com/neondatabase/neon/issues/3865
    4944         1404 :         new_timeline
    4945         1404 :             .remote_client
    4946         1404 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    4947         1404 :             .context("branch initial metadata upload")?;
    4948              : 
    4949              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    4950              : 
    4951         1404 :         Ok(CreateTimelineResult::Created(new_timeline))
    4952         1428 :     }
    4953              : 
    4954              :     /// For unit tests, make this visible so that other modules can directly create timelines
    4955              :     #[cfg(test)]
    4956              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    4957              :     pub(crate) async fn bootstrap_timeline_test(
    4958              :         self: &Arc<Self>,
    4959              :         timeline_id: TimelineId,
    4960              :         pg_version: u32,
    4961              :         load_existing_initdb: Option<TimelineId>,
    4962              :         ctx: &RequestContext,
    4963              :     ) -> anyhow::Result<Arc<Timeline>> {
    4964              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    4965              :             .await
    4966              :             .map_err(anyhow::Error::new)
    4967           12 :             .map(|r| r.into_timeline_for_test())
    4968              :     }
    4969              : 
    4970              :     /// Get exclusive access to the timeline ID for creation.
    4971              :     ///
    4972              :     /// Timeline-creating code paths must use this function before making changes
    4973              :     /// to in-memory or persistent state.
    4974              :     ///
    4975              :     /// The `state` parameter is a description of the timeline creation operation
    4976              :     /// we intend to perform.
    4977              :     /// If the timeline was already created in the meantime, we check whether this
    4978              :     /// request conflicts or is idempotent , based on `state`.
    4979         2796 :     async fn start_creating_timeline(
    4980         2796 :         self: &Arc<Self>,
    4981         2796 :         new_timeline_id: TimelineId,
    4982         2796 :         idempotency: CreateTimelineIdempotency,
    4983         2796 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    4984         2796 :         let allow_offloaded = false;
    4985         2796 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    4986         2784 :             Ok(create_guard) => {
    4987         2784 :                 pausable_failpoint!("timeline-creation-after-uninit");
    4988         2784 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    4989              :             }
    4990            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    4991              :             Err(TimelineExclusionError::AlreadyCreating) => {
    4992              :                 // Creation is in progress, we cannot create it again, and we cannot
    4993              :                 // check if this request matches the existing one, so caller must try
    4994              :                 // again later.
    4995            0 :                 Err(CreateTimelineError::AlreadyCreating)
    4996              :             }
    4997            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    4998              :             Err(TimelineExclusionError::AlreadyExists {
    4999            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    5000            0 :                 ..
    5001            0 :             }) => {
    5002            0 :                 info!("timeline already exists but is offloaded");
    5003            0 :                 Err(CreateTimelineError::Conflict)
    5004              :             }
    5005              :             Err(TimelineExclusionError::AlreadyExists {
    5006           12 :                 existing: TimelineOrOffloaded::Timeline(existing),
    5007           12 :                 arg,
    5008           12 :             }) => {
    5009           12 :                 {
    5010           12 :                     let existing = &existing.create_idempotency;
    5011           12 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    5012           12 :                     debug!("timeline already exists");
    5013              : 
    5014           12 :                     match (existing, &arg) {
    5015              :                         // FailWithConflict => no idempotency check
    5016              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5017              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5018           12 :                             warn!("timeline already exists, failing request");
    5019           12 :                             return Err(CreateTimelineError::Conflict);
    5020              :                         }
    5021              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    5022            0 :                         (x, y) if x == y => {
    5023            0 :                             info!(
    5024            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    5025              :                             );
    5026              :                             // fallthrough
    5027              :                         }
    5028              :                         (_, _) => {
    5029            0 :                             warn!("idempotency conflict, failing request");
    5030            0 :                             return Err(CreateTimelineError::Conflict);
    5031              :                         }
    5032              :                     }
    5033              :                 }
    5034              : 
    5035            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5036              :             }
    5037              :         }
    5038         2796 :     }
    5039              : 
    5040            0 :     async fn upload_initdb(
    5041            0 :         &self,
    5042            0 :         timelines_path: &Utf8PathBuf,
    5043            0 :         pgdata_path: &Utf8PathBuf,
    5044            0 :         timeline_id: &TimelineId,
    5045            0 :     ) -> anyhow::Result<()> {
    5046            0 :         let temp_path = timelines_path.join(format!(
    5047            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5048            0 :         ));
    5049            0 : 
    5050            0 :         scopeguard::defer! {
    5051            0 :             if let Err(e) = fs::remove_file(&temp_path) {
    5052            0 :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5053            0 :             }
    5054            0 :         }
    5055              : 
    5056            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5057              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5058            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5059            0 :             warn!(
    5060            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5061              :             );
    5062            0 :         }
    5063              : 
    5064            0 :         pausable_failpoint!("before-initdb-upload");
    5065              : 
    5066            0 :         backoff::retry(
    5067            0 :             || async {
    5068            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5069            0 :                     &self.remote_storage,
    5070            0 :                     &self.tenant_shard_id.tenant_id,
    5071            0 :                     timeline_id,
    5072            0 :                     pgdata_zstd.try_clone().await?,
    5073            0 :                     tar_zst_size,
    5074            0 :                     &self.cancel,
    5075            0 :                 )
    5076            0 :                 .await
    5077            0 :             },
    5078            0 :             |_| false,
    5079            0 :             3,
    5080            0 :             u32::MAX,
    5081            0 :             "persist_initdb_tar_zst",
    5082            0 :             &self.cancel,
    5083            0 :         )
    5084            0 :         .await
    5085            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5086            0 :         .and_then(|x| x)
    5087            0 :     }
    5088              : 
    5089              :     /// - run initdb to init temporary instance and get bootstrap data
    5090              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5091           12 :     async fn bootstrap_timeline(
    5092           12 :         self: &Arc<Self>,
    5093           12 :         timeline_id: TimelineId,
    5094           12 :         pg_version: u32,
    5095           12 :         load_existing_initdb: Option<TimelineId>,
    5096           12 :         ctx: &RequestContext,
    5097           12 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5098           12 :         let timeline_create_guard = match self
    5099           12 :             .start_creating_timeline(
    5100           12 :                 timeline_id,
    5101           12 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5102           12 :             )
    5103           12 :             .await?
    5104              :         {
    5105           12 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5106            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5107            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5108              :             }
    5109              :         };
    5110              : 
    5111              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5112              :         // temporary directory for basebackup files for the given timeline.
    5113              : 
    5114           12 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5115           12 :         let pgdata_path = path_with_suffix_extension(
    5116           12 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5117           12 :             TEMP_FILE_SUFFIX,
    5118           12 :         );
    5119           12 : 
    5120           12 :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5121           12 :         // we won't race with other creations or existent timelines with the same path.
    5122           12 :         if pgdata_path.exists() {
    5123            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5124            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5125            0 :             })?;
    5126            0 :             tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
    5127           12 :         }
    5128              : 
    5129              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5130           12 :         let pgdata_path_deferred = pgdata_path.clone();
    5131           12 :         scopeguard::defer! {
    5132           12 :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5133           12 :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5134           12 :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5135           12 :             } else {
    5136           12 :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5137           12 :             }
    5138           12 :         }
    5139           12 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5140           12 :             if existing_initdb_timeline_id != timeline_id {
    5141            0 :                 let source_path = &remote_initdb_archive_path(
    5142            0 :                     &self.tenant_shard_id.tenant_id,
    5143            0 :                     &existing_initdb_timeline_id,
    5144            0 :                 );
    5145            0 :                 let dest_path =
    5146            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5147            0 : 
    5148            0 :                 // if this fails, it will get retried by retried control plane requests
    5149            0 :                 self.remote_storage
    5150            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5151            0 :                     .await
    5152            0 :                     .context("copy initdb tar")?;
    5153           12 :             }
    5154           12 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5155           12 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5156           12 :                     self.conf,
    5157           12 :                     &self.remote_storage,
    5158           12 :                     &self.tenant_shard_id,
    5159           12 :                     &existing_initdb_timeline_id,
    5160           12 :                     &self.cancel,
    5161           12 :                 )
    5162           12 :                 .await
    5163           12 :                 .context("download initdb tar")?;
    5164              : 
    5165           12 :             scopeguard::defer! {
    5166           12 :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5167           12 :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5168           12 :                 }
    5169           12 :             }
    5170           12 : 
    5171           12 :             let buf_read =
    5172           12 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5173           12 :             extract_zst_tarball(&pgdata_path, buf_read)
    5174           12 :                 .await
    5175           12 :                 .context("extract initdb tar")?;
    5176              :         } else {
    5177              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5178            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5179            0 :                 .await
    5180            0 :                 .context("run initdb")?;
    5181              : 
    5182              :             // Upload the created data dir to S3
    5183            0 :             if self.tenant_shard_id().is_shard_zero() {
    5184            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5185            0 :                     .await?;
    5186            0 :             }
    5187              :         }
    5188           12 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5189           12 : 
    5190           12 :         // Import the contents of the data directory at the initial checkpoint
    5191           12 :         // LSN, and any WAL after that.
    5192           12 :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5193           12 :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5194           12 :         let new_metadata = TimelineMetadata::new(
    5195           12 :             Lsn(0),
    5196           12 :             None,
    5197           12 :             None,
    5198           12 :             Lsn(0),
    5199           12 :             pgdata_lsn,
    5200           12 :             pgdata_lsn,
    5201           12 :             pg_version,
    5202           12 :         );
    5203           12 :         let (mut raw_timeline, timeline_ctx) = self
    5204           12 :             .prepare_new_timeline(
    5205           12 :                 timeline_id,
    5206           12 :                 &new_metadata,
    5207           12 :                 timeline_create_guard,
    5208           12 :                 pgdata_lsn,
    5209           12 :                 None,
    5210           12 :                 None,
    5211           12 :                 ctx,
    5212           12 :             )
    5213           12 :             .await?;
    5214              : 
    5215           12 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5216           12 :         raw_timeline
    5217           12 :             .write(|unfinished_timeline| async move {
    5218           12 :                 import_datadir::import_timeline_from_postgres_datadir(
    5219           12 :                     &unfinished_timeline,
    5220           12 :                     &pgdata_path,
    5221           12 :                     pgdata_lsn,
    5222           12 :                     &timeline_ctx,
    5223           12 :                 )
    5224           12 :                 .await
    5225           12 :                 .with_context(|| {
    5226            0 :                     format!(
    5227            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5228            0 :                     )
    5229           12 :                 })?;
    5230              : 
    5231           12 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5232            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5233            0 :                         "failpoint before-checkpoint-new-timeline"
    5234            0 :                     )))
    5235           12 :                 });
    5236              : 
    5237           12 :                 Ok(())
    5238           24 :             })
    5239           12 :             .await?;
    5240              : 
    5241              :         // All done!
    5242           12 :         let timeline = raw_timeline.finish_creation().await?;
    5243              : 
    5244              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5245              : 
    5246           12 :         Ok(CreateTimelineResult::Created(timeline))
    5247           12 :     }
    5248              : 
    5249         2760 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5250         2760 :         RemoteTimelineClient::new(
    5251         2760 :             self.remote_storage.clone(),
    5252         2760 :             self.deletion_queue_client.clone(),
    5253         2760 :             self.conf,
    5254         2760 :             self.tenant_shard_id,
    5255         2760 :             timeline_id,
    5256         2760 :             self.generation,
    5257         2760 :             &self.tenant_conf.load().location,
    5258         2760 :         )
    5259         2760 :     }
    5260              : 
    5261              :     /// Builds required resources for a new timeline.
    5262         2760 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5263         2760 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5264         2760 :         self.get_timeline_resources_for(remote_client)
    5265         2760 :     }
    5266              : 
    5267              :     /// Builds timeline resources for the given remote client.
    5268         2796 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5269         2796 :         TimelineResources {
    5270         2796 :             remote_client,
    5271         2796 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5272         2796 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5273         2796 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5274         2796 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5275         2796 :         }
    5276         2796 :     }
    5277              : 
    5278              :     /// Creates intermediate timeline structure and its files.
    5279              :     ///
    5280              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5281              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5282              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5283              :     #[allow(clippy::too_many_arguments)]
    5284         2760 :     async fn prepare_new_timeline<'a>(
    5285         2760 :         &'a self,
    5286         2760 :         new_timeline_id: TimelineId,
    5287         2760 :         new_metadata: &TimelineMetadata,
    5288         2760 :         create_guard: TimelineCreateGuard,
    5289         2760 :         start_lsn: Lsn,
    5290         2760 :         ancestor: Option<Arc<Timeline>>,
    5291         2760 :         rel_size_v2_status: Option<RelSizeMigration>,
    5292         2760 :         ctx: &RequestContext,
    5293         2760 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5294         2760 :         let tenant_shard_id = self.tenant_shard_id;
    5295         2760 : 
    5296         2760 :         let resources = self.build_timeline_resources(new_timeline_id);
    5297         2760 :         resources
    5298         2760 :             .remote_client
    5299         2760 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5300              : 
    5301         2760 :         let (timeline_struct, timeline_ctx) = self
    5302         2760 :             .create_timeline_struct(
    5303         2760 :                 new_timeline_id,
    5304         2760 :                 new_metadata,
    5305         2760 :                 None,
    5306         2760 :                 ancestor,
    5307         2760 :                 resources,
    5308         2760 :                 CreateTimelineCause::Load,
    5309         2760 :                 create_guard.idempotency.clone(),
    5310         2760 :                 None,
    5311         2760 :                 rel_size_v2_status,
    5312         2760 :                 ctx,
    5313         2760 :             )
    5314         2760 :             .context("Failed to create timeline data structure")?;
    5315              : 
    5316         2760 :         timeline_struct.init_empty_layer_map(start_lsn);
    5317              : 
    5318         2760 :         if let Err(e) = self
    5319         2760 :             .create_timeline_files(&create_guard.timeline_path)
    5320         2760 :             .await
    5321              :         {
    5322            0 :             error!(
    5323            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5324              :             );
    5325            0 :             cleanup_timeline_directory(create_guard);
    5326            0 :             return Err(e);
    5327         2760 :         }
    5328         2760 : 
    5329         2760 :         debug!(
    5330            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5331              :         );
    5332              : 
    5333         2760 :         Ok((
    5334         2760 :             UninitializedTimeline::new(
    5335         2760 :                 self,
    5336         2760 :                 new_timeline_id,
    5337         2760 :                 Some((timeline_struct, create_guard)),
    5338         2760 :             ),
    5339         2760 :             timeline_ctx,
    5340         2760 :         ))
    5341         2760 :     }
    5342              : 
    5343         2760 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5344         2760 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5345              : 
    5346         2760 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5347            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5348         2760 :         });
    5349              : 
    5350         2760 :         Ok(())
    5351         2760 :     }
    5352              : 
    5353              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5354              :     /// concurrent attempts to create the same timeline.
    5355              :     ///
    5356              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5357              :     /// offloaded timelines or not.
    5358         2796 :     fn create_timeline_create_guard(
    5359         2796 :         self: &Arc<Self>,
    5360         2796 :         timeline_id: TimelineId,
    5361         2796 :         idempotency: CreateTimelineIdempotency,
    5362         2796 :         allow_offloaded: bool,
    5363         2796 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5364         2796 :         let tenant_shard_id = self.tenant_shard_id;
    5365         2796 : 
    5366         2796 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5367              : 
    5368         2796 :         let create_guard = TimelineCreateGuard::new(
    5369         2796 :             self,
    5370         2796 :             timeline_id,
    5371         2796 :             timeline_path.clone(),
    5372         2796 :             idempotency,
    5373         2796 :             allow_offloaded,
    5374         2796 :         )?;
    5375              : 
    5376              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5377              :         // for creation.
    5378              :         // A timeline directory should never exist on disk already:
    5379              :         // - a previous failed creation would have cleaned up after itself
    5380              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5381              :         //
    5382              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5383              :         // this error may indicate a bug in cleanup on failed creations.
    5384         2784 :         if timeline_path.exists() {
    5385            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5386            0 :                 "Timeline directory already exists! This is a bug."
    5387            0 :             )));
    5388         2784 :         }
    5389         2784 : 
    5390         2784 :         Ok(create_guard)
    5391         2796 :     }
    5392              : 
    5393              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5394              :     ///
    5395              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5396              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5397              :     pub async fn gather_size_inputs(
    5398              :         &self,
    5399              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5400              :         // (only if it is shorter than the real cutoff).
    5401              :         max_retention_period: Option<u64>,
    5402              :         cause: LogicalSizeCalculationCause,
    5403              :         cancel: &CancellationToken,
    5404              :         ctx: &RequestContext,
    5405              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5406              :         let logical_sizes_at_once = self
    5407              :             .conf
    5408              :             .concurrent_tenant_size_logical_size_queries
    5409              :             .inner();
    5410              : 
    5411              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5412              :         //
    5413              :         // But the only case where we need to run multiple of these at once is when we
    5414              :         // request a size for a tenant manually via API, while another background calculation
    5415              :         // is in progress (which is not a common case).
    5416              :         //
    5417              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5418              :         let mut shared_cache = tokio::select! {
    5419              :             locked = self.cached_logical_sizes.lock() => locked,
    5420              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5421              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5422              :         };
    5423              : 
    5424              :         size::gather_inputs(
    5425              :             self,
    5426              :             logical_sizes_at_once,
    5427              :             max_retention_period,
    5428              :             &mut shared_cache,
    5429              :             cause,
    5430              :             cancel,
    5431              :             ctx,
    5432              :         )
    5433              :         .await
    5434              :     }
    5435              : 
    5436              :     /// Calculate synthetic tenant size and cache the result.
    5437              :     /// This is periodically called by background worker.
    5438              :     /// result is cached in tenant struct
    5439              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5440              :     pub async fn calculate_synthetic_size(
    5441              :         &self,
    5442              :         cause: LogicalSizeCalculationCause,
    5443              :         cancel: &CancellationToken,
    5444              :         ctx: &RequestContext,
    5445              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5446              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5447              : 
    5448              :         let size = inputs.calculate();
    5449              : 
    5450              :         self.set_cached_synthetic_size(size);
    5451              : 
    5452              :         Ok(size)
    5453              :     }
    5454              : 
    5455              :     /// Cache given synthetic size and update the metric value
    5456            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5457            0 :         self.cached_synthetic_tenant_size
    5458            0 :             .store(size, Ordering::Relaxed);
    5459            0 : 
    5460            0 :         // Only shard zero should be calculating synthetic sizes
    5461            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5462              : 
    5463            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5464            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5465            0 :             .unwrap()
    5466            0 :             .set(size);
    5467            0 :     }
    5468              : 
    5469            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5470            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5471            0 :     }
    5472              : 
    5473              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5474              :     ///
    5475              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5476              :     /// from an external API handler.
    5477              :     ///
    5478              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5479              :     /// still bounded by tenant/timeline shutdown.
    5480              :     #[tracing::instrument(skip_all)]
    5481              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5482              :         let timelines = self.timelines.lock().unwrap().clone();
    5483              : 
    5484            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5485            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5486            0 :             timeline.freeze_and_flush().await?;
    5487            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5488            0 :             timeline.remote_client.wait_completion().await?;
    5489              : 
    5490            0 :             Ok(())
    5491            0 :         }
    5492              : 
    5493              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5494              :         // aborted when this function's future is cancelled: they should stay alive
    5495              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5496              :         // before Timeline shutdown completes.
    5497              :         let mut results = FuturesUnordered::new();
    5498              : 
    5499              :         for (_timeline_id, timeline) in timelines {
    5500              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5501              :             // means that if this function's future is cancelled, the Timeline shutdown
    5502              :             // will still wait for any I/O in here to complete.
    5503              :             let Ok(gate) = timeline.gate.enter() else {
    5504              :                 continue;
    5505              :             };
    5506            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5507              :             results.push(jh);
    5508              :         }
    5509              : 
    5510              :         while let Some(r) = results.next().await {
    5511              :             if let Err(e) = r {
    5512              :                 if !e.is_cancelled() && !e.is_panic() {
    5513              :                     tracing::error!("unexpected join error: {e:?}");
    5514              :                 }
    5515              :             }
    5516              :         }
    5517              : 
    5518              :         // The flushes we did above were just writes, but the TenantShard might have had
    5519              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5520              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5521              :         // because it's typically a no-op.
    5522              :         match self.deletion_queue_client.flush_execute().await {
    5523              :             Ok(_) => {}
    5524              :             Err(DeletionQueueError::ShuttingDown) => {}
    5525              :         }
    5526              : 
    5527              :         Ok(())
    5528              :     }
    5529              : 
    5530            0 :     pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
    5531            0 :         self.tenant_conf.load().tenant_conf.clone()
    5532            0 :     }
    5533              : 
    5534              :     /// How much local storage would this tenant like to have?  It can cope with
    5535              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5536              :     /// the TenantShard to advertise how much storage it would prefer to have to provide fast I/O
    5537              :     /// by keeping important things on local disk.
    5538              :     ///
    5539              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5540              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5541              :     /// actually use more than they report here.
    5542            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5543            0 :         let timelines = self.timelines.lock().unwrap();
    5544            0 : 
    5545            0 :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5546            0 :         // reflects the observation that on tenants with multiple large branches, typically only one
    5547            0 :         // of them is used actively enough to occupy space on disk.
    5548            0 :         timelines
    5549            0 :             .values()
    5550            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5551            0 :             .max()
    5552            0 :             .unwrap_or(0)
    5553            0 :     }
    5554              : 
    5555              :     /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
    5556              :     /// manifest in `Self::remote_tenant_manifest`.
    5557              :     ///
    5558              :     /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
    5559              :     /// changing any `TenantShard` state that's included in the manifest, consider making the manifest
    5560              :     /// the authoritative source of data with an API that automatically uploads on changes. Revisit
    5561              :     /// this when the manifest is more widely used and we have a better idea of the data model.
    5562         1416 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5563              :         // Multiple tasks may call this function concurrently after mutating the TenantShard runtime
    5564              :         // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
    5565              :         // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
    5566              :         // simple coalescing mechanism.
    5567         1416 :         let mut guard = tokio::select! {
    5568         1416 :             guard = self.remote_tenant_manifest.lock() => guard,
    5569         1416 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5570              :         };
    5571              : 
    5572              :         // Build a new manifest.
    5573         1416 :         let manifest = self.build_tenant_manifest();
    5574              : 
    5575              :         // Check if the manifest has changed. We ignore the version number here, to avoid
    5576              :         // uploading every manifest on version number bumps.
    5577         1416 :         if let Some(old) = guard.as_ref() {
    5578           48 :             if manifest.eq_ignoring_version(old) {
    5579           36 :                 return Ok(());
    5580           12 :             }
    5581         1368 :         }
    5582              : 
    5583              :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5584         1380 :         match backoff::retry(
    5585         1380 :             || async {
    5586         1380 :                 upload_tenant_manifest(
    5587         1380 :                     &self.remote_storage,
    5588         1380 :                     &self.tenant_shard_id,
    5589         1380 :                     self.generation,
    5590         1380 :                     &manifest,
    5591         1380 :                     &self.cancel,
    5592         1380 :                 )
    5593         1380 :                 .await
    5594         2760 :             },
    5595         1380 :             |_| self.cancel.is_cancelled(),
    5596         1380 :             FAILED_UPLOAD_WARN_THRESHOLD,
    5597         1380 :             FAILED_REMOTE_OP_RETRIES,
    5598         1380 :             "uploading tenant manifest",
    5599         1380 :             &self.cancel,
    5600         1380 :         )
    5601         1380 :         .await
    5602              :         {
    5603            0 :             None => Err(TenantManifestError::Cancelled),
    5604            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5605            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5606              :             Some(Ok(_)) => {
    5607              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5608              :                 // re-uploading the same thing.
    5609         1380 :                 *guard = Some(manifest);
    5610         1380 : 
    5611         1380 :                 Ok(())
    5612              :             }
    5613              :         }
    5614         1416 :     }
    5615              : }
    5616              : 
    5617              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5618              : /// to get bootstrap data for timeline initialization.
    5619            0 : async fn run_initdb(
    5620            0 :     conf: &'static PageServerConf,
    5621            0 :     initdb_target_dir: &Utf8Path,
    5622            0 :     pg_version: u32,
    5623            0 :     cancel: &CancellationToken,
    5624            0 : ) -> Result<(), InitdbError> {
    5625            0 :     let initdb_bin_path = conf
    5626            0 :         .pg_bin_dir(pg_version)
    5627            0 :         .map_err(InitdbError::Other)?
    5628            0 :         .join("initdb");
    5629            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5630            0 :     info!(
    5631            0 :         "running {} in {}, libdir: {}",
    5632              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5633              :     );
    5634              : 
    5635            0 :     let _permit = {
    5636            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5637            0 :         INIT_DB_SEMAPHORE.acquire().await
    5638              :     };
    5639              : 
    5640            0 :     CONCURRENT_INITDBS.inc();
    5641            0 :     scopeguard::defer! {
    5642            0 :         CONCURRENT_INITDBS.dec();
    5643            0 :     }
    5644            0 : 
    5645            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5646            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5647            0 :         superuser: &conf.superuser,
    5648            0 :         locale: &conf.locale,
    5649            0 :         initdb_bin: &initdb_bin_path,
    5650            0 :         pg_version,
    5651            0 :         library_search_path: &initdb_lib_dir,
    5652            0 :         pgdata: initdb_target_dir,
    5653            0 :     })
    5654            0 :     .await
    5655            0 :     .map_err(InitdbError::Inner);
    5656            0 : 
    5657            0 :     // This isn't true cancellation support, see above. Still return an error to
    5658            0 :     // excercise the cancellation code path.
    5659            0 :     if cancel.is_cancelled() {
    5660            0 :         return Err(InitdbError::Cancelled);
    5661            0 :     }
    5662            0 : 
    5663            0 :     res
    5664            0 : }
    5665              : 
    5666              : /// Dump contents of a layer file to stdout.
    5667            0 : pub async fn dump_layerfile_from_path(
    5668            0 :     path: &Utf8Path,
    5669            0 :     verbose: bool,
    5670            0 :     ctx: &RequestContext,
    5671            0 : ) -> anyhow::Result<()> {
    5672              :     use std::os::unix::fs::FileExt;
    5673              : 
    5674              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5675              :     // file.
    5676            0 :     let file = File::open(path)?;
    5677            0 :     let mut header_buf = [0u8; 2];
    5678            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5679              : 
    5680            0 :     match u16::from_be_bytes(header_buf) {
    5681              :         crate::IMAGE_FILE_MAGIC => {
    5682            0 :             ImageLayer::new_for_path(path, file)?
    5683            0 :                 .dump(verbose, ctx)
    5684            0 :                 .await?
    5685              :         }
    5686              :         crate::DELTA_FILE_MAGIC => {
    5687            0 :             DeltaLayer::new_for_path(path, file)?
    5688            0 :                 .dump(verbose, ctx)
    5689            0 :                 .await?
    5690              :         }
    5691            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5692              :     }
    5693              : 
    5694            0 :     Ok(())
    5695            0 : }
    5696              : 
    5697              : #[cfg(test)]
    5698              : pub(crate) mod harness {
    5699              :     use bytes::{Bytes, BytesMut};
    5700              :     use hex_literal::hex;
    5701              :     use once_cell::sync::OnceCell;
    5702              :     use pageserver_api::key::Key;
    5703              :     use pageserver_api::models::ShardParameters;
    5704              :     use pageserver_api::record::NeonWalRecord;
    5705              :     use pageserver_api::shard::ShardIndex;
    5706              :     use utils::id::TenantId;
    5707              :     use utils::logging;
    5708              : 
    5709              :     use super::*;
    5710              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5711              :     use crate::l0_flush::L0FlushConfig;
    5712              :     use crate::walredo::apply_neon;
    5713              : 
    5714              :     pub const TIMELINE_ID: TimelineId =
    5715              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5716              :     pub const NEW_TIMELINE_ID: TimelineId =
    5717              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5718              : 
    5719              :     /// Convenience function to create a page image with given string as the only content
    5720     30172675 :     pub fn test_img(s: &str) -> Bytes {
    5721     30172675 :         let mut buf = BytesMut::new();
    5722     30172675 :         buf.extend_from_slice(s.as_bytes());
    5723     30172675 :         buf.resize(64, 0);
    5724     30172675 : 
    5725     30172675 :         buf.freeze()
    5726     30172675 :     }
    5727              : 
    5728              :     pub struct TenantHarness {
    5729              :         pub conf: &'static PageServerConf,
    5730              :         pub tenant_conf: pageserver_api::models::TenantConfig,
    5731              :         pub tenant_shard_id: TenantShardId,
    5732              :         pub generation: Generation,
    5733              :         pub shard: ShardIndex,
    5734              :         pub remote_storage: GenericRemoteStorage,
    5735              :         pub remote_fs_dir: Utf8PathBuf,
    5736              :         pub deletion_queue: MockDeletionQueue,
    5737              :     }
    5738              : 
    5739              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5740              : 
    5741         1548 :     pub(crate) fn setup_logging() {
    5742         1548 :         LOG_HANDLE.get_or_init(|| {
    5743         1476 :             logging::init(
    5744         1476 :                 logging::LogFormat::Test,
    5745         1476 :                 // enable it in case the tests exercise code paths that use
    5746         1476 :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5747         1476 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5748         1476 :                 logging::Output::Stdout,
    5749         1476 :             )
    5750         1476 :             .expect("Failed to init test logging");
    5751         1548 :         });
    5752         1548 :     }
    5753              : 
    5754              :     impl TenantHarness {
    5755         1404 :         pub async fn create_custom(
    5756         1404 :             test_name: &'static str,
    5757         1404 :             tenant_conf: pageserver_api::models::TenantConfig,
    5758         1404 :             tenant_id: TenantId,
    5759         1404 :             shard_identity: ShardIdentity,
    5760         1404 :             generation: Generation,
    5761         1404 :         ) -> anyhow::Result<Self> {
    5762         1404 :             setup_logging();
    5763         1404 : 
    5764         1404 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5765         1404 :             let _ = fs::remove_dir_all(&repo_dir);
    5766         1404 :             fs::create_dir_all(&repo_dir)?;
    5767              : 
    5768         1404 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5769         1404 :             // Make a static copy of the config. This can never be free'd, but that's
    5770         1404 :             // OK in a test.
    5771         1404 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5772         1404 : 
    5773         1404 :             let shard = shard_identity.shard_index();
    5774         1404 :             let tenant_shard_id = TenantShardId {
    5775         1404 :                 tenant_id,
    5776         1404 :                 shard_number: shard.shard_number,
    5777         1404 :                 shard_count: shard.shard_count,
    5778         1404 :             };
    5779         1404 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5780         1404 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5781              : 
    5782              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5783         1404 :             let remote_fs_dir = conf.workdir.join("localfs");
    5784         1404 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5785         1404 :             let config = RemoteStorageConfig {
    5786         1404 :                 storage: RemoteStorageKind::LocalFs {
    5787         1404 :                     local_path: remote_fs_dir.clone(),
    5788         1404 :                 },
    5789         1404 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5790         1404 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5791         1404 :             };
    5792         1404 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5793         1404 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5794         1404 : 
    5795         1404 :             Ok(Self {
    5796         1404 :                 conf,
    5797         1404 :                 tenant_conf,
    5798         1404 :                 tenant_shard_id,
    5799         1404 :                 generation,
    5800         1404 :                 shard,
    5801         1404 :                 remote_storage,
    5802         1404 :                 remote_fs_dir,
    5803         1404 :                 deletion_queue,
    5804         1404 :             })
    5805         1404 :         }
    5806              : 
    5807         1320 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5808         1320 :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5809         1320 :             // The tests perform them manually if needed.
    5810         1320 :             let tenant_conf = pageserver_api::models::TenantConfig {
    5811         1320 :                 gc_period: Some(Duration::ZERO),
    5812         1320 :                 compaction_period: Some(Duration::ZERO),
    5813         1320 :                 ..Default::default()
    5814         1320 :             };
    5815         1320 :             let tenant_id = TenantId::generate();
    5816         1320 :             let shard = ShardIdentity::unsharded();
    5817         1320 :             Self::create_custom(
    5818         1320 :                 test_name,
    5819         1320 :                 tenant_conf,
    5820         1320 :                 tenant_id,
    5821         1320 :                 shard,
    5822         1320 :                 Generation::new(0xdeadbeef),
    5823         1320 :             )
    5824         1320 :             .await
    5825         1320 :         }
    5826              : 
    5827          120 :         pub fn span(&self) -> tracing::Span {
    5828          120 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5829          120 :         }
    5830              : 
    5831         1404 :         pub(crate) async fn load(&self) -> (Arc<TenantShard>, RequestContext) {
    5832         1404 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    5833         1404 :                 .with_scope_unit_test();
    5834         1404 :             (
    5835         1404 :                 self.do_try_load(&ctx)
    5836         1404 :                     .await
    5837         1404 :                     .expect("failed to load test tenant"),
    5838         1404 :                 ctx,
    5839         1404 :             )
    5840         1404 :         }
    5841              : 
    5842              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5843              :         pub(crate) async fn do_try_load(
    5844              :             &self,
    5845              :             ctx: &RequestContext,
    5846              :         ) -> anyhow::Result<Arc<TenantShard>> {
    5847              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    5848              : 
    5849              :             let tenant = Arc::new(TenantShard::new(
    5850              :                 TenantState::Attaching,
    5851              :                 self.conf,
    5852              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    5853              :                     self.tenant_conf.clone(),
    5854              :                     self.generation,
    5855              :                     &ShardParameters::default(),
    5856              :                 ))
    5857              :                 .unwrap(),
    5858              :                 // This is a legacy/test code path: sharding isn't supported here.
    5859              :                 ShardIdentity::unsharded(),
    5860              :                 Some(walredo_mgr),
    5861              :                 self.tenant_shard_id,
    5862              :                 self.remote_storage.clone(),
    5863              :                 self.deletion_queue.new_client(),
    5864              :                 // TODO: ideally we should run all unit tests with both configs
    5865              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    5866              :             ));
    5867              : 
    5868              :             let preload = tenant
    5869              :                 .preload(&self.remote_storage, CancellationToken::new())
    5870              :                 .await?;
    5871              :             tenant.attach(Some(preload), ctx).await?;
    5872              : 
    5873              :             tenant.state.send_replace(TenantState::Active);
    5874              :             for timeline in tenant.timelines.lock().unwrap().values() {
    5875              :                 timeline.set_state(TimelineState::Active);
    5876              :             }
    5877              :             Ok(tenant)
    5878              :         }
    5879              : 
    5880           12 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    5881           12 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    5882           12 :         }
    5883              :     }
    5884              : 
    5885              :     // Mock WAL redo manager that doesn't do much
    5886              :     pub(crate) struct TestRedoManager;
    5887              : 
    5888              :     impl TestRedoManager {
    5889              :         /// # Cancel-Safety
    5890              :         ///
    5891              :         /// This method is cancellation-safe.
    5892       321288 :         pub async fn request_redo(
    5893       321288 :             &self,
    5894       321288 :             key: Key,
    5895       321288 :             lsn: Lsn,
    5896       321288 :             base_img: Option<(Lsn, Bytes)>,
    5897       321288 :             records: Vec<(Lsn, NeonWalRecord)>,
    5898       321288 :             _pg_version: u32,
    5899       321288 :             _redo_attempt_type: RedoAttemptType,
    5900       321288 :         ) -> Result<Bytes, walredo::Error> {
    5901     16842120 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    5902       321288 :             if records_neon {
    5903              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    5904       321288 :                 let mut page = match (base_img, records.first()) {
    5905       156348 :                     (Some((_lsn, img)), _) => {
    5906       156348 :                         let mut page = BytesMut::new();
    5907       156348 :                         page.extend_from_slice(&img);
    5908       156348 :                         page
    5909              :                     }
    5910       164940 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    5911              :                     _ => {
    5912            0 :                         panic!("Neon WAL redo requires base image or will init record");
    5913              :                     }
    5914              :                 };
    5915              : 
    5916     17163396 :                 for (record_lsn, record) in records {
    5917     16842120 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    5918              :                 }
    5919       321276 :                 Ok(page.freeze())
    5920              :             } else {
    5921              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    5922            0 :                 let s = format!(
    5923            0 :                     "redo for {} to get to {}, with {} and {} records",
    5924            0 :                     key,
    5925            0 :                     lsn,
    5926            0 :                     if base_img.is_some() {
    5927            0 :                         "base image"
    5928              :                     } else {
    5929            0 :                         "no base image"
    5930              :                     },
    5931            0 :                     records.len()
    5932            0 :                 );
    5933            0 :                 println!("{s}");
    5934            0 : 
    5935            0 :                 Ok(test_img(&s))
    5936              :             }
    5937       321288 :         }
    5938              :     }
    5939              : }
    5940              : 
    5941              : #[cfg(test)]
    5942              : mod tests {
    5943              :     use std::collections::{BTreeMap, BTreeSet};
    5944              : 
    5945              :     use bytes::{Bytes, BytesMut};
    5946              :     use hex_literal::hex;
    5947              :     use itertools::Itertools;
    5948              :     #[cfg(feature = "testing")]
    5949              :     use models::CompactLsnRange;
    5950              :     use pageserver_api::key::{
    5951              :         AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX, repl_origin_key,
    5952              :     };
    5953              :     use pageserver_api::keyspace::KeySpace;
    5954              :     #[cfg(feature = "testing")]
    5955              :     use pageserver_api::keyspace::KeySpaceRandomAccum;
    5956              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    5957              :     #[cfg(feature = "testing")]
    5958              :     use pageserver_api::record::NeonWalRecord;
    5959              :     use pageserver_api::value::Value;
    5960              :     use pageserver_compaction::helpers::overlaps_with;
    5961              :     #[cfg(feature = "testing")]
    5962              :     use rand::SeedableRng;
    5963              :     #[cfg(feature = "testing")]
    5964              :     use rand::rngs::StdRng;
    5965              :     use rand::{Rng, thread_rng};
    5966              :     #[cfg(feature = "testing")]
    5967              :     use std::ops::Range;
    5968              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    5969              :     use tests::storage_layer::ValuesReconstructState;
    5970              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    5971              :     #[cfg(feature = "testing")]
    5972              :     use timeline::GcInfo;
    5973              :     #[cfg(feature = "testing")]
    5974              :     use timeline::InMemoryLayerTestDesc;
    5975              :     #[cfg(feature = "testing")]
    5976              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    5977              :     use timeline::{CompactOptions, DeltaLayerTestDesc, VersionedKeySpaceQuery};
    5978              :     use utils::id::TenantId;
    5979              : 
    5980              :     use super::*;
    5981              :     use crate::DEFAULT_PG_VERSION;
    5982              :     use crate::keyspace::KeySpaceAccum;
    5983              :     use crate::tenant::harness::*;
    5984              :     use crate::tenant::timeline::CompactFlags;
    5985              : 
    5986              :     static TEST_KEY: Lazy<Key> =
    5987          108 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    5988              : 
    5989              :     #[cfg(feature = "testing")]
    5990              :     struct TestTimelineSpecification {
    5991              :         start_lsn: Lsn,
    5992              :         last_record_lsn: Lsn,
    5993              : 
    5994              :         in_memory_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    5995              :         delta_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    5996              :         image_layers_shape: Vec<(Range<Key>, Lsn)>,
    5997              : 
    5998              :         gap_chance: u8,
    5999              :         will_init_chance: u8,
    6000              :     }
    6001              : 
    6002              :     #[cfg(feature = "testing")]
    6003              :     struct Storage {
    6004              :         storage: HashMap<(Key, Lsn), Value>,
    6005              :         start_lsn: Lsn,
    6006              :     }
    6007              : 
    6008              :     #[cfg(feature = "testing")]
    6009              :     impl Storage {
    6010       384000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    6011              :             use bytes::BufMut;
    6012              : 
    6013       384000 :             let mut crnt_lsn = lsn;
    6014       384000 :             let mut got_base = false;
    6015       384000 : 
    6016       384000 :             let mut acc = Vec::new();
    6017              : 
    6018     33982452 :             while crnt_lsn >= self.start_lsn {
    6019     33982452 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6020     17054064 :                     acc.push(value.clone());
    6021              : 
    6022     16834572 :                     match value {
    6023     16834572 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6024     16834572 :                             if *will_init {
    6025       164508 :                                 got_base = true;
    6026       164508 :                                 break;
    6027     16670064 :                             }
    6028              :                         }
    6029              :                         Value::Image(_) => {
    6030       219492 :                             got_base = true;
    6031       219492 :                             break;
    6032              :                         }
    6033            0 :                         _ => unreachable!(),
    6034              :                     }
    6035     16928388 :                 }
    6036              : 
    6037     33598452 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6038              :             }
    6039              : 
    6040       384000 :             assert!(
    6041       384000 :                 got_base,
    6042            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6043              :             );
    6044              : 
    6045       384000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6046              : 
    6047       384000 :             let mut blob = BytesMut::new();
    6048     17054064 :             for value in acc.into_iter().rev() {
    6049     16834572 :                 match value {
    6050     16834572 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6051     16834572 :                         blob.extend_from_slice(append.as_bytes());
    6052     16834572 :                     }
    6053       219492 :                     Value::Image(img) => {
    6054       219492 :                         blob.put(img);
    6055       219492 :                     }
    6056            0 :                     _ => unreachable!(),
    6057              :                 }
    6058              :             }
    6059              : 
    6060       384000 :             blob.into()
    6061       384000 :         }
    6062              :     }
    6063              : 
    6064              :     #[cfg(feature = "testing")]
    6065              :     #[allow(clippy::too_many_arguments)]
    6066           12 :     async fn randomize_timeline(
    6067           12 :         tenant: &Arc<TenantShard>,
    6068           12 :         new_timeline_id: TimelineId,
    6069           12 :         pg_version: u32,
    6070           12 :         spec: TestTimelineSpecification,
    6071           12 :         random: &mut rand::rngs::StdRng,
    6072           12 :         ctx: &RequestContext,
    6073           12 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6074           12 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6075           12 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6076              : 
    6077           24 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6078           24 :             let mut lsn = lsn_range.start;
    6079         2424 :             while lsn < lsn_range.end {
    6080         2400 :                 let mut key = key_range.start;
    6081       252216 :                 while key < key_range.end {
    6082       249816 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6083       249816 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6084       249816 : 
    6085       249816 :                     if gap {
    6086        12216 :                         continue;
    6087       237600 :                     }
    6088              : 
    6089       237600 :                     let record = if will_init {
    6090         2292 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6091              :                     } else {
    6092       235308 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6093              :                     };
    6094              : 
    6095       237600 :                     storage.insert((key, lsn), record);
    6096       237600 : 
    6097       237600 :                     key = key.next();
    6098              :                 }
    6099         2400 :                 lsn = Lsn(lsn.0 + 1);
    6100              :             }
    6101              : 
    6102              :             // Stash some interesting LSN for future use
    6103           72 :             for offset in [0, 5, 100].iter() {
    6104           72 :                 if *offset == 0 {
    6105           24 :                     interesting_lsns.push(lsn_range.start);
    6106           24 :                 } else {
    6107           48 :                     let below = lsn_range.start.checked_sub(*offset);
    6108           48 :                     match below {
    6109           48 :                         Some(v) if v >= spec.start_lsn => {
    6110           48 :                             interesting_lsns.push(v);
    6111           48 :                         }
    6112            0 :                         _ => {}
    6113              :                     }
    6114              : 
    6115           48 :                     let above = Lsn(lsn_range.start.0 + offset);
    6116           48 :                     interesting_lsns.push(above);
    6117              :                 }
    6118              :             }
    6119              :         }
    6120              : 
    6121           36 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6122           36 :             let mut lsn = lsn_range.start;
    6123         3780 :             while lsn < lsn_range.end {
    6124         3744 :                 let mut key = key_range.start;
    6125       133344 :                 while key < key_range.end {
    6126       129600 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6127       129600 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6128       129600 : 
    6129       129600 :                     if gap {
    6130         6048 :                         continue;
    6131       123552 :                     }
    6132              : 
    6133       123552 :                     let record = if will_init {
    6134         1236 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6135              :                     } else {
    6136       122316 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6137              :                     };
    6138              : 
    6139       123552 :                     storage.insert((key, lsn), record);
    6140       123552 : 
    6141       123552 :                     key = key.next();
    6142              :                 }
    6143         3744 :                 lsn = Lsn(lsn.0 + 1);
    6144              :             }
    6145              : 
    6146              :             // Stash some interesting LSN for future use
    6147          108 :             for offset in [0, 5, 100].iter() {
    6148          108 :                 if *offset == 0 {
    6149           36 :                     interesting_lsns.push(lsn_range.start);
    6150           36 :                 } else {
    6151           72 :                     let below = lsn_range.start.checked_sub(*offset);
    6152           72 :                     match below {
    6153           72 :                         Some(v) if v >= spec.start_lsn => {
    6154           36 :                             interesting_lsns.push(v);
    6155           36 :                         }
    6156           36 :                         _ => {}
    6157              :                     }
    6158              : 
    6159           72 :                     let above = Lsn(lsn_range.start.0 + offset);
    6160           72 :                     interesting_lsns.push(above);
    6161              :                 }
    6162              :             }
    6163              :         }
    6164              : 
    6165           36 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6166           36 :             let mut key = key_range.start;
    6167         1704 :             while key < key_range.end {
    6168         1668 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6169         1668 :                 let record = Value::Image(blob.clone());
    6170         1668 :                 storage.insert((key, *lsn), record);
    6171         1668 : 
    6172         1668 :                 key = key.next();
    6173         1668 :             }
    6174              : 
    6175              :             // Stash some interesting LSN for future use
    6176          108 :             for offset in [0, 5, 100].iter() {
    6177          108 :                 if *offset == 0 {
    6178           36 :                     interesting_lsns.push(*lsn);
    6179           36 :                 } else {
    6180           72 :                     let below = lsn.checked_sub(*offset);
    6181           72 :                     match below {
    6182           72 :                         Some(v) if v >= spec.start_lsn => {
    6183           48 :                             interesting_lsns.push(v);
    6184           48 :                         }
    6185           24 :                         _ => {}
    6186              :                     }
    6187              : 
    6188           72 :                     let above = Lsn(lsn.0 + offset);
    6189           72 :                     interesting_lsns.push(above);
    6190              :                 }
    6191              :             }
    6192              :         }
    6193              : 
    6194           12 :         let in_memory_test_layers = {
    6195           12 :             let mut acc = Vec::new();
    6196              : 
    6197           24 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6198           24 :                 let mut data = Vec::new();
    6199           24 : 
    6200           24 :                 let mut lsn = lsn_range.start;
    6201         2424 :                 while lsn < lsn_range.end {
    6202         2400 :                     let mut key = key_range.start;
    6203       240000 :                     while key < key_range.end {
    6204       237600 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6205       237600 :                             data.push((key, lsn, record.clone()));
    6206       237600 :                         }
    6207              : 
    6208       237600 :                         key = key.next();
    6209              :                     }
    6210         2400 :                     lsn = Lsn(lsn.0 + 1);
    6211              :                 }
    6212              : 
    6213           24 :                 acc.push(InMemoryLayerTestDesc {
    6214           24 :                     data,
    6215           24 :                     lsn_range: lsn_range.clone(),
    6216           24 :                     is_open: false,
    6217           24 :                 })
    6218              :             }
    6219              : 
    6220           12 :             acc
    6221              :         };
    6222              : 
    6223           12 :         let delta_test_layers = {
    6224           12 :             let mut acc = Vec::new();
    6225              : 
    6226           36 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6227           36 :                 let mut data = Vec::new();
    6228           36 : 
    6229           36 :                 let mut lsn = lsn_range.start;
    6230         3780 :                 while lsn < lsn_range.end {
    6231         3744 :                     let mut key = key_range.start;
    6232       127296 :                     while key < key_range.end {
    6233       123552 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6234       123552 :                             data.push((key, lsn, record.clone()));
    6235       123552 :                         }
    6236              : 
    6237       123552 :                         key = key.next();
    6238              :                     }
    6239         3744 :                     lsn = Lsn(lsn.0 + 1);
    6240              :                 }
    6241              : 
    6242           36 :                 acc.push(DeltaLayerTestDesc {
    6243           36 :                     data,
    6244           36 :                     lsn_range: lsn_range.clone(),
    6245           36 :                     key_range: key_range.clone(),
    6246           36 :                 })
    6247              :             }
    6248              : 
    6249           12 :             acc
    6250              :         };
    6251              : 
    6252           12 :         let image_test_layers = {
    6253           12 :             let mut acc = Vec::new();
    6254              : 
    6255           36 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6256           36 :                 let mut data = Vec::new();
    6257           36 : 
    6258           36 :                 let mut key = key_range.start;
    6259         1704 :                 while key < key_range.end {
    6260         1668 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6261         1668 :                         let blob = match record {
    6262         1668 :                             Value::Image(blob) => blob.clone(),
    6263            0 :                             _ => unreachable!(),
    6264              :                         };
    6265              : 
    6266         1668 :                         data.push((key, blob));
    6267            0 :                     }
    6268              : 
    6269         1668 :                     key = key.next();
    6270              :                 }
    6271              : 
    6272           36 :                 acc.push((*lsn, data));
    6273              :             }
    6274              : 
    6275           12 :             acc
    6276              :         };
    6277              : 
    6278           12 :         let tline = tenant
    6279           12 :             .create_test_timeline_with_layers(
    6280           12 :                 new_timeline_id,
    6281           12 :                 spec.start_lsn,
    6282           12 :                 pg_version,
    6283           12 :                 ctx,
    6284           12 :                 in_memory_test_layers,
    6285           12 :                 delta_test_layers,
    6286           12 :                 image_test_layers,
    6287           12 :                 spec.last_record_lsn,
    6288           12 :             )
    6289           12 :             .await?;
    6290              : 
    6291           12 :         Ok((
    6292           12 :             tline,
    6293           12 :             Storage {
    6294           12 :                 storage,
    6295           12 :                 start_lsn: spec.start_lsn,
    6296           12 :             },
    6297           12 :             interesting_lsns,
    6298           12 :         ))
    6299           12 :     }
    6300              : 
    6301              :     #[tokio::test]
    6302           12 :     async fn test_basic() -> anyhow::Result<()> {
    6303           12 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6304           12 :         let tline = tenant
    6305           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6306           12 :             .await?;
    6307           12 : 
    6308           12 :         let mut writer = tline.writer().await;
    6309           12 :         writer
    6310           12 :             .put(
    6311           12 :                 *TEST_KEY,
    6312           12 :                 Lsn(0x10),
    6313           12 :                 &Value::Image(test_img("foo at 0x10")),
    6314           12 :                 &ctx,
    6315           12 :             )
    6316           12 :             .await?;
    6317           12 :         writer.finish_write(Lsn(0x10));
    6318           12 :         drop(writer);
    6319           12 : 
    6320           12 :         let mut writer = tline.writer().await;
    6321           12 :         writer
    6322           12 :             .put(
    6323           12 :                 *TEST_KEY,
    6324           12 :                 Lsn(0x20),
    6325           12 :                 &Value::Image(test_img("foo at 0x20")),
    6326           12 :                 &ctx,
    6327           12 :             )
    6328           12 :             .await?;
    6329           12 :         writer.finish_write(Lsn(0x20));
    6330           12 :         drop(writer);
    6331           12 : 
    6332           12 :         assert_eq!(
    6333           12 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6334           12 :             test_img("foo at 0x10")
    6335           12 :         );
    6336           12 :         assert_eq!(
    6337           12 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6338           12 :             test_img("foo at 0x10")
    6339           12 :         );
    6340           12 :         assert_eq!(
    6341           12 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6342           12 :             test_img("foo at 0x20")
    6343           12 :         );
    6344           12 : 
    6345           12 :         Ok(())
    6346           12 :     }
    6347              : 
    6348              :     #[tokio::test]
    6349           12 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6350           12 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6351           12 :             .await?
    6352           12 :             .load()
    6353           12 :             .await;
    6354           12 :         let _ = tenant
    6355           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6356           12 :             .await?;
    6357           12 : 
    6358           12 :         match tenant
    6359           12 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6360           12 :             .await
    6361           12 :         {
    6362           12 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6363           12 :             Err(e) => assert_eq!(
    6364           12 :                 e.to_string(),
    6365           12 :                 "timeline already exists with different parameters".to_string()
    6366           12 :             ),
    6367           12 :         }
    6368           12 : 
    6369           12 :         Ok(())
    6370           12 :     }
    6371              : 
    6372              :     /// Convenience function to create a page image with given string as the only content
    6373           60 :     pub fn test_value(s: &str) -> Value {
    6374           60 :         let mut buf = BytesMut::new();
    6375           60 :         buf.extend_from_slice(s.as_bytes());
    6376           60 :         Value::Image(buf.freeze())
    6377           60 :     }
    6378              : 
    6379              :     ///
    6380              :     /// Test branch creation
    6381              :     ///
    6382              :     #[tokio::test]
    6383           12 :     async fn test_branch() -> anyhow::Result<()> {
    6384           12 :         use std::str::from_utf8;
    6385           12 : 
    6386           12 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6387           12 :         let tline = tenant
    6388           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6389           12 :             .await?;
    6390           12 :         let mut writer = tline.writer().await;
    6391           12 : 
    6392           12 :         #[allow(non_snake_case)]
    6393           12 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6394           12 :         #[allow(non_snake_case)]
    6395           12 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6396           12 : 
    6397           12 :         // Insert a value on the timeline
    6398           12 :         writer
    6399           12 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6400           12 :             .await?;
    6401           12 :         writer
    6402           12 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6403           12 :             .await?;
    6404           12 :         writer.finish_write(Lsn(0x20));
    6405           12 : 
    6406           12 :         writer
    6407           12 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6408           12 :             .await?;
    6409           12 :         writer.finish_write(Lsn(0x30));
    6410           12 :         writer
    6411           12 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6412           12 :             .await?;
    6413           12 :         writer.finish_write(Lsn(0x40));
    6414           12 : 
    6415           12 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6416           12 : 
    6417           12 :         // Branch the history, modify relation differently on the new timeline
    6418           12 :         tenant
    6419           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6420           12 :             .await?;
    6421           12 :         let newtline = tenant
    6422           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6423           12 :             .expect("Should have a local timeline");
    6424           12 :         let mut new_writer = newtline.writer().await;
    6425           12 :         new_writer
    6426           12 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6427           12 :             .await?;
    6428           12 :         new_writer.finish_write(Lsn(0x40));
    6429           12 : 
    6430           12 :         // Check page contents on both branches
    6431           12 :         assert_eq!(
    6432           12 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6433           12 :             "foo at 0x40"
    6434           12 :         );
    6435           12 :         assert_eq!(
    6436           12 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6437           12 :             "bar at 0x40"
    6438           12 :         );
    6439           12 :         assert_eq!(
    6440           12 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6441           12 :             "foobar at 0x20"
    6442           12 :         );
    6443           12 : 
    6444           12 :         //assert_current_logical_size(&tline, Lsn(0x40));
    6445           12 : 
    6446           12 :         Ok(())
    6447           12 :     }
    6448              : 
    6449          120 :     async fn make_some_layers(
    6450          120 :         tline: &Timeline,
    6451          120 :         start_lsn: Lsn,
    6452          120 :         ctx: &RequestContext,
    6453          120 :     ) -> anyhow::Result<()> {
    6454          120 :         let mut lsn = start_lsn;
    6455              :         {
    6456          120 :             let mut writer = tline.writer().await;
    6457              :             // Create a relation on the timeline
    6458          120 :             writer
    6459          120 :                 .put(
    6460          120 :                     *TEST_KEY,
    6461          120 :                     lsn,
    6462          120 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6463          120 :                     ctx,
    6464          120 :                 )
    6465          120 :                 .await?;
    6466          120 :             writer.finish_write(lsn);
    6467          120 :             lsn += 0x10;
    6468          120 :             writer
    6469          120 :                 .put(
    6470          120 :                     *TEST_KEY,
    6471          120 :                     lsn,
    6472          120 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6473          120 :                     ctx,
    6474          120 :                 )
    6475          120 :                 .await?;
    6476          120 :             writer.finish_write(lsn);
    6477          120 :             lsn += 0x10;
    6478          120 :         }
    6479          120 :         tline.freeze_and_flush().await?;
    6480              :         {
    6481          120 :             let mut writer = tline.writer().await;
    6482          120 :             writer
    6483          120 :                 .put(
    6484          120 :                     *TEST_KEY,
    6485          120 :                     lsn,
    6486          120 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6487          120 :                     ctx,
    6488          120 :                 )
    6489          120 :                 .await?;
    6490          120 :             writer.finish_write(lsn);
    6491          120 :             lsn += 0x10;
    6492          120 :             writer
    6493          120 :                 .put(
    6494          120 :                     *TEST_KEY,
    6495          120 :                     lsn,
    6496          120 :                     &Value::Image(test_img(&format!("foo at {}", lsn))),
    6497          120 :                     ctx,
    6498          120 :                 )
    6499          120 :                 .await?;
    6500          120 :             writer.finish_write(lsn);
    6501          120 :         }
    6502          120 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6503          120 :     }
    6504              : 
    6505              :     #[tokio::test(start_paused = true)]
    6506           12 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6507           12 :         let (tenant, ctx) =
    6508           12 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6509           12 :                 .await?
    6510           12 :                 .load()
    6511           12 :                 .await;
    6512           12 :         // Advance to the lsn lease deadline so that GC is not blocked by
    6513           12 :         // initial transition into AttachedSingle.
    6514           12 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6515           12 :         tokio::time::resume();
    6516           12 :         let tline = tenant
    6517           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6518           12 :             .await?;
    6519           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6520           12 : 
    6521           12 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6522           12 :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6523           12 :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6524           12 :         // below should fail.
    6525           12 :         tenant
    6526           12 :             .gc_iteration(
    6527           12 :                 Some(TIMELINE_ID),
    6528           12 :                 0x10,
    6529           12 :                 Duration::ZERO,
    6530           12 :                 &CancellationToken::new(),
    6531           12 :                 &ctx,
    6532           12 :             )
    6533           12 :             .await?;
    6534           12 : 
    6535           12 :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6536           12 :         match tenant
    6537           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6538           12 :             .await
    6539           12 :         {
    6540           12 :             Ok(_) => panic!("branching should have failed"),
    6541           12 :             Err(err) => {
    6542           12 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6543           12 :                     panic!("wrong error type")
    6544           12 :                 };
    6545           12 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6546           12 :                 assert!(
    6547           12 :                     err.source()
    6548           12 :                         .unwrap()
    6549           12 :                         .to_string()
    6550           12 :                         .contains("we might've already garbage collected needed data")
    6551           12 :                 )
    6552           12 :             }
    6553           12 :         }
    6554           12 : 
    6555           12 :         Ok(())
    6556           12 :     }
    6557              : 
    6558              :     #[tokio::test]
    6559           12 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6560           12 :         let (tenant, ctx) =
    6561           12 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6562           12 :                 .await?
    6563           12 :                 .load()
    6564           12 :                 .await;
    6565           12 : 
    6566           12 :         let tline = tenant
    6567           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6568           12 :             .await?;
    6569           12 :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6570           12 :         match tenant
    6571           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6572           12 :             .await
    6573           12 :         {
    6574           12 :             Ok(_) => panic!("branching should have failed"),
    6575           12 :             Err(err) => {
    6576           12 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6577           12 :                     panic!("wrong error type");
    6578           12 :                 };
    6579           12 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6580           12 :                 assert!(
    6581           12 :                     &err.source()
    6582           12 :                         .unwrap()
    6583           12 :                         .to_string()
    6584           12 :                         .contains("is earlier than latest GC cutoff")
    6585           12 :                 );
    6586           12 :             }
    6587           12 :         }
    6588           12 : 
    6589           12 :         Ok(())
    6590           12 :     }
    6591              : 
    6592              :     /*
    6593              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6594              :     // remove the old value, we'd need to work a little harder
    6595              :     #[tokio::test]
    6596              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6597              :         let repo =
    6598              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6599              :             .load();
    6600              : 
    6601              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6602              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6603              : 
    6604              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6605              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6606              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6607              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6608              :             Ok(_) => panic!("request for page should have failed"),
    6609              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6610              :         }
    6611              :         Ok(())
    6612              :     }
    6613              :      */
    6614              : 
    6615              :     #[tokio::test]
    6616           12 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6617           12 :         let (tenant, ctx) =
    6618           12 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6619           12 :                 .await?
    6620           12 :                 .load()
    6621           12 :                 .await;
    6622           12 :         let tline = tenant
    6623           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6624           12 :             .await?;
    6625           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6626           12 : 
    6627           12 :         tenant
    6628           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6629           12 :             .await?;
    6630           12 :         let newtline = tenant
    6631           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6632           12 :             .expect("Should have a local timeline");
    6633           12 : 
    6634           12 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6635           12 : 
    6636           12 :         tline.set_broken("test".to_owned());
    6637           12 : 
    6638           12 :         tenant
    6639           12 :             .gc_iteration(
    6640           12 :                 Some(TIMELINE_ID),
    6641           12 :                 0x10,
    6642           12 :                 Duration::ZERO,
    6643           12 :                 &CancellationToken::new(),
    6644           12 :                 &ctx,
    6645           12 :             )
    6646           12 :             .await?;
    6647           12 : 
    6648           12 :         // The branchpoints should contain all timelines, even ones marked
    6649           12 :         // as Broken.
    6650           12 :         {
    6651           12 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6652           12 :             assert_eq!(branchpoints.len(), 1);
    6653           12 :             assert_eq!(
    6654           12 :                 branchpoints[0],
    6655           12 :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6656           12 :             );
    6657           12 :         }
    6658           12 : 
    6659           12 :         // You can read the key from the child branch even though the parent is
    6660           12 :         // Broken, as long as you don't need to access data from the parent.
    6661           12 :         assert_eq!(
    6662           12 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6663           12 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6664           12 :         );
    6665           12 : 
    6666           12 :         // This needs to traverse to the parent, and fails.
    6667           12 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6668           12 :         assert!(
    6669           12 :             err.to_string().starts_with(&format!(
    6670           12 :                 "bad state on timeline {}: Broken",
    6671           12 :                 tline.timeline_id
    6672           12 :             )),
    6673           12 :             "{err}"
    6674           12 :         );
    6675           12 : 
    6676           12 :         Ok(())
    6677           12 :     }
    6678              : 
    6679              :     #[tokio::test]
    6680           12 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6681           12 :         let (tenant, ctx) =
    6682           12 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6683           12 :                 .await?
    6684           12 :                 .load()
    6685           12 :                 .await;
    6686           12 :         let tline = tenant
    6687           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6688           12 :             .await?;
    6689           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6690           12 : 
    6691           12 :         tenant
    6692           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6693           12 :             .await?;
    6694           12 :         let newtline = tenant
    6695           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6696           12 :             .expect("Should have a local timeline");
    6697           12 :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6698           12 :         tenant
    6699           12 :             .gc_iteration(
    6700           12 :                 Some(TIMELINE_ID),
    6701           12 :                 0x10,
    6702           12 :                 Duration::ZERO,
    6703           12 :                 &CancellationToken::new(),
    6704           12 :                 &ctx,
    6705           12 :             )
    6706           12 :             .await?;
    6707           12 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6708           12 : 
    6709           12 :         Ok(())
    6710           12 :     }
    6711              :     #[tokio::test]
    6712           12 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6713           12 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6714           12 :             .await?
    6715           12 :             .load()
    6716           12 :             .await;
    6717           12 :         let tline = tenant
    6718           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6719           12 :             .await?;
    6720           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6721           12 : 
    6722           12 :         tenant
    6723           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6724           12 :             .await?;
    6725           12 :         let newtline = tenant
    6726           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6727           12 :             .expect("Should have a local timeline");
    6728           12 : 
    6729           12 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6730           12 : 
    6731           12 :         // run gc on parent
    6732           12 :         tenant
    6733           12 :             .gc_iteration(
    6734           12 :                 Some(TIMELINE_ID),
    6735           12 :                 0x10,
    6736           12 :                 Duration::ZERO,
    6737           12 :                 &CancellationToken::new(),
    6738           12 :                 &ctx,
    6739           12 :             )
    6740           12 :             .await?;
    6741           12 : 
    6742           12 :         // Check that the data is still accessible on the branch.
    6743           12 :         assert_eq!(
    6744           12 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6745           12 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6746           12 :         );
    6747           12 : 
    6748           12 :         Ok(())
    6749           12 :     }
    6750              : 
    6751              :     #[tokio::test]
    6752           12 :     async fn timeline_load() -> anyhow::Result<()> {
    6753           12 :         const TEST_NAME: &str = "timeline_load";
    6754           12 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6755           12 :         {
    6756           12 :             let (tenant, ctx) = harness.load().await;
    6757           12 :             let tline = tenant
    6758           12 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6759           12 :                 .await?;
    6760           12 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6761           12 :             // so that all uploads finish & we can call harness.load() below again
    6762           12 :             tenant
    6763           12 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6764           12 :                 .instrument(harness.span())
    6765           12 :                 .await
    6766           12 :                 .ok()
    6767           12 :                 .unwrap();
    6768           12 :         }
    6769           12 : 
    6770           12 :         let (tenant, _ctx) = harness.load().await;
    6771           12 :         tenant
    6772           12 :             .get_timeline(TIMELINE_ID, true)
    6773           12 :             .expect("cannot load timeline");
    6774           12 : 
    6775           12 :         Ok(())
    6776           12 :     }
    6777              : 
    6778              :     #[tokio::test]
    6779           12 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6780           12 :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6781           12 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6782           12 :         // create two timelines
    6783           12 :         {
    6784           12 :             let (tenant, ctx) = harness.load().await;
    6785           12 :             let tline = tenant
    6786           12 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6787           12 :                 .await?;
    6788           12 : 
    6789           12 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6790           12 : 
    6791           12 :             let child_tline = tenant
    6792           12 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6793           12 :                 .await?;
    6794           12 :             child_tline.set_state(TimelineState::Active);
    6795           12 : 
    6796           12 :             let newtline = tenant
    6797           12 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6798           12 :                 .expect("Should have a local timeline");
    6799           12 : 
    6800           12 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6801           12 : 
    6802           12 :             // so that all uploads finish & we can call harness.load() below again
    6803           12 :             tenant
    6804           12 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6805           12 :                 .instrument(harness.span())
    6806           12 :                 .await
    6807           12 :                 .ok()
    6808           12 :                 .unwrap();
    6809           12 :         }
    6810           12 : 
    6811           12 :         // check that both of them are initially unloaded
    6812           12 :         let (tenant, _ctx) = harness.load().await;
    6813           12 : 
    6814           12 :         // check that both, child and ancestor are loaded
    6815           12 :         let _child_tline = tenant
    6816           12 :             .get_timeline(NEW_TIMELINE_ID, true)
    6817           12 :             .expect("cannot get child timeline loaded");
    6818           12 : 
    6819           12 :         let _ancestor_tline = tenant
    6820           12 :             .get_timeline(TIMELINE_ID, true)
    6821           12 :             .expect("cannot get ancestor timeline loaded");
    6822           12 : 
    6823           12 :         Ok(())
    6824           12 :     }
    6825              : 
    6826              :     #[tokio::test]
    6827           12 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6828           12 :         use storage_layer::AsLayerDesc;
    6829           12 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    6830           12 :             .await?
    6831           12 :             .load()
    6832           12 :             .await;
    6833           12 :         let tline = tenant
    6834           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6835           12 :             .await?;
    6836           12 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6837           12 : 
    6838           12 :         let layer_map = tline.layers.read().await;
    6839           12 :         let level0_deltas = layer_map
    6840           12 :             .layer_map()?
    6841           12 :             .level0_deltas()
    6842           12 :             .iter()
    6843           24 :             .map(|desc| layer_map.get_from_desc(desc))
    6844           12 :             .collect::<Vec<_>>();
    6845           12 : 
    6846           12 :         assert!(!level0_deltas.is_empty());
    6847           12 : 
    6848           36 :         for delta in level0_deltas {
    6849           12 :             // Ensure we are dumping a delta layer here
    6850           24 :             assert!(delta.layer_desc().is_delta);
    6851           24 :             delta.dump(true, &ctx).await.unwrap();
    6852           12 :         }
    6853           12 : 
    6854           12 :         Ok(())
    6855           12 :     }
    6856              : 
    6857              :     #[tokio::test]
    6858           12 :     async fn test_images() -> anyhow::Result<()> {
    6859           12 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    6860           12 :         let tline = tenant
    6861           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6862           12 :             .await?;
    6863           12 : 
    6864           12 :         let mut writer = tline.writer().await;
    6865           12 :         writer
    6866           12 :             .put(
    6867           12 :                 *TEST_KEY,
    6868           12 :                 Lsn(0x10),
    6869           12 :                 &Value::Image(test_img("foo at 0x10")),
    6870           12 :                 &ctx,
    6871           12 :             )
    6872           12 :             .await?;
    6873           12 :         writer.finish_write(Lsn(0x10));
    6874           12 :         drop(writer);
    6875           12 : 
    6876           12 :         tline.freeze_and_flush().await?;
    6877           12 :         tline
    6878           12 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6879           12 :             .await?;
    6880           12 : 
    6881           12 :         let mut writer = tline.writer().await;
    6882           12 :         writer
    6883           12 :             .put(
    6884           12 :                 *TEST_KEY,
    6885           12 :                 Lsn(0x20),
    6886           12 :                 &Value::Image(test_img("foo at 0x20")),
    6887           12 :                 &ctx,
    6888           12 :             )
    6889           12 :             .await?;
    6890           12 :         writer.finish_write(Lsn(0x20));
    6891           12 :         drop(writer);
    6892           12 : 
    6893           12 :         tline.freeze_and_flush().await?;
    6894           12 :         tline
    6895           12 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6896           12 :             .await?;
    6897           12 : 
    6898           12 :         let mut writer = tline.writer().await;
    6899           12 :         writer
    6900           12 :             .put(
    6901           12 :                 *TEST_KEY,
    6902           12 :                 Lsn(0x30),
    6903           12 :                 &Value::Image(test_img("foo at 0x30")),
    6904           12 :                 &ctx,
    6905           12 :             )
    6906           12 :             .await?;
    6907           12 :         writer.finish_write(Lsn(0x30));
    6908           12 :         drop(writer);
    6909           12 : 
    6910           12 :         tline.freeze_and_flush().await?;
    6911           12 :         tline
    6912           12 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6913           12 :             .await?;
    6914           12 : 
    6915           12 :         let mut writer = tline.writer().await;
    6916           12 :         writer
    6917           12 :             .put(
    6918           12 :                 *TEST_KEY,
    6919           12 :                 Lsn(0x40),
    6920           12 :                 &Value::Image(test_img("foo at 0x40")),
    6921           12 :                 &ctx,
    6922           12 :             )
    6923           12 :             .await?;
    6924           12 :         writer.finish_write(Lsn(0x40));
    6925           12 :         drop(writer);
    6926           12 : 
    6927           12 :         tline.freeze_and_flush().await?;
    6928           12 :         tline
    6929           12 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    6930           12 :             .await?;
    6931           12 : 
    6932           12 :         assert_eq!(
    6933           12 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6934           12 :             test_img("foo at 0x10")
    6935           12 :         );
    6936           12 :         assert_eq!(
    6937           12 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6938           12 :             test_img("foo at 0x10")
    6939           12 :         );
    6940           12 :         assert_eq!(
    6941           12 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6942           12 :             test_img("foo at 0x20")
    6943           12 :         );
    6944           12 :         assert_eq!(
    6945           12 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    6946           12 :             test_img("foo at 0x30")
    6947           12 :         );
    6948           12 :         assert_eq!(
    6949           12 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    6950           12 :             test_img("foo at 0x40")
    6951           12 :         );
    6952           12 : 
    6953           12 :         Ok(())
    6954           12 :     }
    6955              : 
    6956           24 :     async fn bulk_insert_compact_gc(
    6957           24 :         tenant: &TenantShard,
    6958           24 :         timeline: &Arc<Timeline>,
    6959           24 :         ctx: &RequestContext,
    6960           24 :         lsn: Lsn,
    6961           24 :         repeat: usize,
    6962           24 :         key_count: usize,
    6963           24 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6964           24 :         let compact = true;
    6965           24 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    6966           24 :     }
    6967              : 
    6968           48 :     async fn bulk_insert_maybe_compact_gc(
    6969           48 :         tenant: &TenantShard,
    6970           48 :         timeline: &Arc<Timeline>,
    6971           48 :         ctx: &RequestContext,
    6972           48 :         mut lsn: Lsn,
    6973           48 :         repeat: usize,
    6974           48 :         key_count: usize,
    6975           48 :         compact: bool,
    6976           48 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    6977           48 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    6978           48 : 
    6979           48 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    6980           48 :         let mut blknum = 0;
    6981           48 : 
    6982           48 :         // Enforce that key range is monotonously increasing
    6983           48 :         let mut keyspace = KeySpaceAccum::new();
    6984           48 : 
    6985           48 :         let cancel = CancellationToken::new();
    6986           48 : 
    6987           48 :         for _ in 0..repeat {
    6988         2400 :             for _ in 0..key_count {
    6989     24000000 :                 test_key.field6 = blknum;
    6990     24000000 :                 let mut writer = timeline.writer().await;
    6991     24000000 :                 writer
    6992     24000000 :                     .put(
    6993     24000000 :                         test_key,
    6994     24000000 :                         lsn,
    6995     24000000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    6996     24000000 :                         ctx,
    6997     24000000 :                     )
    6998     24000000 :                     .await?;
    6999     24000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    7000     24000000 :                 writer.finish_write(lsn);
    7001     24000000 :                 drop(writer);
    7002     24000000 : 
    7003     24000000 :                 keyspace.add_key(test_key);
    7004     24000000 : 
    7005     24000000 :                 lsn = Lsn(lsn.0 + 0x10);
    7006     24000000 :                 blknum += 1;
    7007              :             }
    7008              : 
    7009         2400 :             timeline.freeze_and_flush().await?;
    7010         2400 :             if compact {
    7011              :                 // this requires timeline to be &Arc<Timeline>
    7012         1200 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    7013         1200 :             }
    7014              : 
    7015              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    7016              :             // originally was.
    7017         2400 :             let res = tenant
    7018         2400 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7019         2400 :                 .await?;
    7020              : 
    7021         2400 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7022              :         }
    7023              : 
    7024           48 :         Ok(inserted)
    7025           48 :     }
    7026              : 
    7027              :     //
    7028              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7029              :     // Repeat 50 times.
    7030              :     //
    7031              :     #[tokio::test]
    7032           12 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7033           12 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7034           12 :         let (tenant, ctx) = harness.load().await;
    7035           12 :         let tline = tenant
    7036           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7037           12 :             .await?;
    7038           12 : 
    7039           12 :         let lsn = Lsn(0x10);
    7040           12 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7041           12 : 
    7042           12 :         Ok(())
    7043           12 :     }
    7044              : 
    7045              :     // Test the vectored get real implementation against a simple sequential implementation.
    7046              :     //
    7047              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    7048              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    7049              :     // grow to the right on the X axis.
    7050              :     //                       [Delta]
    7051              :     //                 [Delta]
    7052              :     //           [Delta]
    7053              :     //    [Delta]
    7054              :     // ------------ Image ---------------
    7055              :     //
    7056              :     // After layer generation we pick the ranges to query as follows:
    7057              :     // 1. The beginning of each delta layer
    7058              :     // 2. At the seam between two adjacent delta layers
    7059              :     //
    7060              :     // There's one major downside to this test: delta layers only contains images,
    7061              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    7062              :     #[tokio::test]
    7063           12 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7064           12 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7065           12 :         let (tenant, ctx) = harness.load().await;
    7066           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7067           12 :         let tline = tenant
    7068           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7069           12 :             .await?;
    7070           12 : 
    7071           12 :         let lsn = Lsn(0x10);
    7072           12 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7073           12 : 
    7074           12 :         let guard = tline.layers.read().await;
    7075           12 :         let lm = guard.layer_map()?;
    7076           12 : 
    7077           12 :         lm.dump(true, &ctx).await?;
    7078           12 : 
    7079           12 :         let mut reads = Vec::new();
    7080           12 :         let mut prev = None;
    7081           72 :         lm.iter_historic_layers().for_each(|desc| {
    7082           72 :             if !desc.is_delta() {
    7083           12 :                 prev = Some(desc.clone());
    7084           12 :                 return;
    7085           60 :             }
    7086           60 : 
    7087           60 :             let start = desc.key_range.start;
    7088           60 :             let end = desc
    7089           60 :                 .key_range
    7090           60 :                 .start
    7091           60 :                 .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
    7092           60 :             reads.push(KeySpace {
    7093           60 :                 ranges: vec![start..end],
    7094           60 :             });
    7095           12 : 
    7096           60 :             if let Some(prev) = &prev {
    7097           60 :                 if !prev.is_delta() {
    7098           60 :                     return;
    7099           12 :                 }
    7100            0 : 
    7101            0 :                 let first_range = Key {
    7102            0 :                     field6: prev.key_range.end.field6 - 4,
    7103            0 :                     ..prev.key_range.end
    7104            0 :                 }..prev.key_range.end;
    7105            0 : 
    7106            0 :                 let second_range = desc.key_range.start..Key {
    7107            0 :                     field6: desc.key_range.start.field6 + 4,
    7108            0 :                     ..desc.key_range.start
    7109            0 :                 };
    7110            0 : 
    7111            0 :                 reads.push(KeySpace {
    7112            0 :                     ranges: vec![first_range, second_range],
    7113            0 :                 });
    7114           12 :             };
    7115           12 : 
    7116           12 :             prev = Some(desc.clone());
    7117           72 :         });
    7118           12 : 
    7119           12 :         drop(guard);
    7120           12 : 
    7121           12 :         // Pick a big LSN such that we query over all the changes.
    7122           12 :         let reads_lsn = Lsn(u64::MAX - 1);
    7123           12 : 
    7124           72 :         for read in reads {
    7125           60 :             info!("Doing vectored read on {:?}", read);
    7126           12 : 
    7127           60 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7128           12 : 
    7129           60 :             let vectored_res = tline
    7130           60 :                 .get_vectored_impl(
    7131           60 :                     query,
    7132           60 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7133           60 :                     &ctx,
    7134           60 :                 )
    7135           60 :                 .await;
    7136           12 : 
    7137           60 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7138           60 :             let mut expect_missing = false;
    7139           60 :             let mut key = read.start().unwrap();
    7140         1980 :             while key != read.end().unwrap() {
    7141         1920 :                 if let Some(lsns) = inserted.get(&key) {
    7142         1920 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7143         1920 :                     match expected_lsn {
    7144         1920 :                         Some(lsn) => {
    7145         1920 :                             expected_lsns.insert(key, *lsn);
    7146         1920 :                         }
    7147           12 :                         None => {
    7148           12 :                             expect_missing = true;
    7149            0 :                             break;
    7150           12 :                         }
    7151           12 :                     }
    7152           12 :                 } else {
    7153           12 :                     expect_missing = true;
    7154            0 :                     break;
    7155           12 :                 }
    7156           12 : 
    7157         1920 :                 key = key.next();
    7158           12 :             }
    7159           12 : 
    7160           60 :             if expect_missing {
    7161           12 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7162           12 :             } else {
    7163         1920 :                 for (key, image) in vectored_res? {
    7164         1920 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7165         1920 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7166         1920 :                     assert_eq!(image?, expected_image);
    7167           12 :                 }
    7168           12 :             }
    7169           12 :         }
    7170           12 : 
    7171           12 :         Ok(())
    7172           12 :     }
    7173              : 
    7174              :     #[tokio::test]
    7175           12 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7176           12 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7177           12 : 
    7178           12 :         let (tenant, ctx) = harness.load().await;
    7179           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7180           12 :         let (tline, ctx) = tenant
    7181           12 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7182           12 :             .await?;
    7183           12 :         let tline = tline.raw_timeline().unwrap();
    7184           12 : 
    7185           12 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7186           12 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7187           12 :         modification.set_lsn(Lsn(0x1008))?;
    7188           12 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7189           12 :         modification.commit(&ctx).await?;
    7190           12 : 
    7191           12 :         let child_timeline_id = TimelineId::generate();
    7192           12 :         tenant
    7193           12 :             .branch_timeline_test(
    7194           12 :                 tline,
    7195           12 :                 child_timeline_id,
    7196           12 :                 Some(tline.get_last_record_lsn()),
    7197           12 :                 &ctx,
    7198           12 :             )
    7199           12 :             .await?;
    7200           12 : 
    7201           12 :         let child_timeline = tenant
    7202           12 :             .get_timeline(child_timeline_id, true)
    7203           12 :             .expect("Should have the branched timeline");
    7204           12 : 
    7205           12 :         let aux_keyspace = KeySpace {
    7206           12 :             ranges: vec![NON_INHERITED_RANGE],
    7207           12 :         };
    7208           12 :         let read_lsn = child_timeline.get_last_record_lsn();
    7209           12 : 
    7210           12 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7211           12 : 
    7212           12 :         let vectored_res = child_timeline
    7213           12 :             .get_vectored_impl(
    7214           12 :                 query,
    7215           12 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7216           12 :                 &ctx,
    7217           12 :             )
    7218           12 :             .await;
    7219           12 : 
    7220           12 :         let images = vectored_res?;
    7221           12 :         assert!(images.is_empty());
    7222           12 :         Ok(())
    7223           12 :     }
    7224              : 
    7225              :     // Test that vectored get handles layer gaps correctly
    7226              :     // by advancing into the next ancestor timeline if required.
    7227              :     //
    7228              :     // The test generates timelines that look like the diagram below.
    7229              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    7230              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    7231              :     //
    7232              :     // ```
    7233              :     //-------------------------------+
    7234              :     //                          ...  |
    7235              :     //               [   L1   ]      |
    7236              :     //     [ / L1   ]                | Child Timeline
    7237              :     // ...                           |
    7238              :     // ------------------------------+
    7239              :     //     [ X L1   ]                | Parent Timeline
    7240              :     // ------------------------------+
    7241              :     // ```
    7242              :     #[tokio::test]
    7243           12 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7244           12 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7245           12 :             // Make compaction deterministic
    7246           12 :             gc_period: Some(Duration::ZERO),
    7247           12 :             compaction_period: Some(Duration::ZERO),
    7248           12 :             // Encourage creation of L1 layers
    7249           12 :             checkpoint_distance: Some(16 * 1024),
    7250           12 :             compaction_target_size: Some(8 * 1024),
    7251           12 :             ..Default::default()
    7252           12 :         };
    7253           12 : 
    7254           12 :         let harness = TenantHarness::create_custom(
    7255           12 :             "test_get_vectored_key_gap",
    7256           12 :             tenant_conf,
    7257           12 :             TenantId::generate(),
    7258           12 :             ShardIdentity::unsharded(),
    7259           12 :             Generation::new(0xdeadbeef),
    7260           12 :         )
    7261           12 :         .await?;
    7262           12 :         let (tenant, ctx) = harness.load().await;
    7263           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7264           12 : 
    7265           12 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7266           12 :         let gap_at_key = current_key.add(100);
    7267           12 :         let mut current_lsn = Lsn(0x10);
    7268           12 : 
    7269           12 :         const KEY_COUNT: usize = 10_000;
    7270           12 : 
    7271           12 :         let timeline_id = TimelineId::generate();
    7272           12 :         let current_timeline = tenant
    7273           12 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7274           12 :             .await?;
    7275           12 : 
    7276           12 :         current_lsn += 0x100;
    7277           12 : 
    7278           12 :         let mut writer = current_timeline.writer().await;
    7279           12 :         writer
    7280           12 :             .put(
    7281           12 :                 gap_at_key,
    7282           12 :                 current_lsn,
    7283           12 :                 &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
    7284           12 :                 &ctx,
    7285           12 :             )
    7286           12 :             .await?;
    7287           12 :         writer.finish_write(current_lsn);
    7288           12 :         drop(writer);
    7289           12 : 
    7290           12 :         let mut latest_lsns = HashMap::new();
    7291           12 :         latest_lsns.insert(gap_at_key, current_lsn);
    7292           12 : 
    7293           12 :         current_timeline.freeze_and_flush().await?;
    7294           12 : 
    7295           12 :         let child_timeline_id = TimelineId::generate();
    7296           12 : 
    7297           12 :         tenant
    7298           12 :             .branch_timeline_test(
    7299           12 :                 &current_timeline,
    7300           12 :                 child_timeline_id,
    7301           12 :                 Some(current_lsn),
    7302           12 :                 &ctx,
    7303           12 :             )
    7304           12 :             .await?;
    7305           12 :         let child_timeline = tenant
    7306           12 :             .get_timeline(child_timeline_id, true)
    7307           12 :             .expect("Should have the branched timeline");
    7308           12 : 
    7309       120012 :         for i in 0..KEY_COUNT {
    7310       120000 :             if current_key == gap_at_key {
    7311           12 :                 current_key = current_key.next();
    7312           12 :                 continue;
    7313       119988 :             }
    7314       119988 : 
    7315       119988 :             current_lsn += 0x10;
    7316           12 : 
    7317       119988 :             let mut writer = child_timeline.writer().await;
    7318       119988 :             writer
    7319       119988 :                 .put(
    7320       119988 :                     current_key,
    7321       119988 :                     current_lsn,
    7322       119988 :                     &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
    7323       119988 :                     &ctx,
    7324       119988 :                 )
    7325       119988 :                 .await?;
    7326       119988 :             writer.finish_write(current_lsn);
    7327       119988 :             drop(writer);
    7328       119988 : 
    7329       119988 :             latest_lsns.insert(current_key, current_lsn);
    7330       119988 :             current_key = current_key.next();
    7331       119988 : 
    7332       119988 :             // Flush every now and then to encourage layer file creation.
    7333       119988 :             if i % 500 == 0 {
    7334          240 :                 child_timeline.freeze_and_flush().await?;
    7335       119748 :             }
    7336           12 :         }
    7337           12 : 
    7338           12 :         child_timeline.freeze_and_flush().await?;
    7339           12 :         let mut flags = EnumSet::new();
    7340           12 :         flags.insert(CompactFlags::ForceRepartition);
    7341           12 :         child_timeline
    7342           12 :             .compact(&CancellationToken::new(), flags, &ctx)
    7343           12 :             .await?;
    7344           12 : 
    7345           12 :         let key_near_end = {
    7346           12 :             let mut tmp = current_key;
    7347           12 :             tmp.field6 -= 10;
    7348           12 :             tmp
    7349           12 :         };
    7350           12 : 
    7351           12 :         let key_near_gap = {
    7352           12 :             let mut tmp = gap_at_key;
    7353           12 :             tmp.field6 -= 10;
    7354           12 :             tmp
    7355           12 :         };
    7356           12 : 
    7357           12 :         let read = KeySpace {
    7358           12 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7359           12 :         };
    7360           12 : 
    7361           12 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7362           12 : 
    7363           12 :         let results = child_timeline
    7364           12 :             .get_vectored_impl(
    7365           12 :                 query,
    7366           12 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7367           12 :                 &ctx,
    7368           12 :             )
    7369           12 :             .await?;
    7370           12 : 
    7371          264 :         for (key, img_res) in results {
    7372          252 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7373          252 :             assert_eq!(img_res?, expected);
    7374           12 :         }
    7375           12 : 
    7376           12 :         Ok(())
    7377           12 :     }
    7378              : 
    7379              :     // Test that vectored get descends into ancestor timelines correctly and
    7380              :     // does not return an image that's newer than requested.
    7381              :     //
    7382              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7383              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7384              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7385              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7386              :     // order to avoid returning an image that's too new. The test below constructs such
    7387              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7388              :     // ```
    7389              :     //    LSN
    7390              :     //     ^
    7391              :     //     |
    7392              :     //     |
    7393              :     // 500 | --------------------------------------> branch point
    7394              :     // 400 |        X
    7395              :     // 300 |        X
    7396              :     // 200 | --------------------------------------> requested lsn
    7397              :     // 100 |        X
    7398              :     //     |---------------------------------------> Key
    7399              :     //              |
    7400              :     //              ------> requested key
    7401              :     //
    7402              :     // Legend:
    7403              :     // * X - page images
    7404              :     // ```
    7405              :     #[tokio::test]
    7406           12 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7407           12 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7408           12 :         let (tenant, ctx) = harness.load().await;
    7409           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7410           12 : 
    7411           12 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7412           12 :         let end_key = start_key.add(1000);
    7413           12 :         let child_gap_at_key = start_key.add(500);
    7414           12 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7415           12 : 
    7416           12 :         let mut current_lsn = Lsn(0x10);
    7417           12 : 
    7418           12 :         let timeline_id = TimelineId::generate();
    7419           12 :         let parent_timeline = tenant
    7420           12 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7421           12 :             .await?;
    7422           12 : 
    7423           12 :         current_lsn += 0x100;
    7424           12 : 
    7425           48 :         for _ in 0..3 {
    7426           36 :             let mut key = start_key;
    7427        36036 :             while key < end_key {
    7428        36000 :                 current_lsn += 0x10;
    7429        36000 : 
    7430        36000 :                 let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
    7431           12 : 
    7432        36000 :                 let mut writer = parent_timeline.writer().await;
    7433        36000 :                 writer
    7434        36000 :                     .put(
    7435        36000 :                         key,
    7436        36000 :                         current_lsn,
    7437        36000 :                         &Value::Image(test_img(&image_value)),
    7438        36000 :                         &ctx,
    7439        36000 :                     )
    7440        36000 :                     .await?;
    7441        36000 :                 writer.finish_write(current_lsn);
    7442        36000 : 
    7443        36000 :                 if key == child_gap_at_key {
    7444           36 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7445        35964 :                 }
    7446           12 : 
    7447        36000 :                 key = key.next();
    7448           12 :             }
    7449           12 : 
    7450           36 :             parent_timeline.freeze_and_flush().await?;
    7451           12 :         }
    7452           12 : 
    7453           12 :         let child_timeline_id = TimelineId::generate();
    7454           12 : 
    7455           12 :         let child_timeline = tenant
    7456           12 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7457           12 :             .await?;
    7458           12 : 
    7459           12 :         let mut key = start_key;
    7460        12012 :         while key < end_key {
    7461        12000 :             if key == child_gap_at_key {
    7462           12 :                 key = key.next();
    7463           12 :                 continue;
    7464        11988 :             }
    7465        11988 : 
    7466        11988 :             current_lsn += 0x10;
    7467           12 : 
    7468        11988 :             let mut writer = child_timeline.writer().await;
    7469        11988 :             writer
    7470        11988 :                 .put(
    7471        11988 :                     key,
    7472        11988 :                     current_lsn,
    7473        11988 :                     &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
    7474        11988 :                     &ctx,
    7475        11988 :                 )
    7476        11988 :                 .await?;
    7477        11988 :             writer.finish_write(current_lsn);
    7478        11988 : 
    7479        11988 :             key = key.next();
    7480           12 :         }
    7481           12 : 
    7482           12 :         child_timeline.freeze_and_flush().await?;
    7483           12 : 
    7484           12 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7485           12 :         let mut query_lsns = Vec::new();
    7486           36 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7487          216 :             for offset in lsn_offsets {
    7488          180 :                 query_lsns.push(Lsn(image_lsn
    7489          180 :                     .0
    7490          180 :                     .checked_add_signed(offset)
    7491          180 :                     .expect("Shouldn't overflow")));
    7492          180 :             }
    7493           12 :         }
    7494           12 : 
    7495          192 :         for query_lsn in query_lsns {
    7496          180 :             let query = VersionedKeySpaceQuery::uniform(
    7497          180 :                 KeySpace {
    7498          180 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7499          180 :                 },
    7500          180 :                 query_lsn,
    7501          180 :             );
    7502           12 : 
    7503          180 :             let results = child_timeline
    7504          180 :                 .get_vectored_impl(
    7505          180 :                     query,
    7506          180 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7507          180 :                     &ctx,
    7508          180 :                 )
    7509          180 :                 .await;
    7510           12 : 
    7511          180 :             let expected_item = parent_gap_lsns
    7512          180 :                 .iter()
    7513          180 :                 .rev()
    7514          408 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7515          180 : 
    7516          180 :             info!(
    7517           12 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7518           12 :                 query_lsn, expected_item
    7519           12 :             );
    7520           12 : 
    7521          180 :             match expected_item {
    7522          156 :                 Some((_, img_value)) => {
    7523          156 :                     let key_results = results.expect("No vectored get error expected");
    7524          156 :                     let key_result = &key_results[&child_gap_at_key];
    7525          156 :                     let returned_img = key_result
    7526          156 :                         .as_ref()
    7527          156 :                         .expect("No page reconstruct error expected");
    7528          156 : 
    7529          156 :                     info!(
    7530           12 :                         "Vectored read at LSN {} returned image {}",
    7531            0 :                         query_lsn,
    7532            0 :                         std::str::from_utf8(returned_img)?
    7533           12 :                     );
    7534          156 :                     assert_eq!(*returned_img, test_img(img_value));
    7535           12 :                 }
    7536           12 :                 None => {
    7537           24 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7538           12 :                 }
    7539           12 :             }
    7540           12 :         }
    7541           12 : 
    7542           12 :         Ok(())
    7543           12 :     }
    7544              : 
    7545              :     #[tokio::test]
    7546           12 :     async fn test_random_updates() -> anyhow::Result<()> {
    7547           12 :         let names_algorithms = [
    7548           12 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7549           12 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7550           12 :         ];
    7551           36 :         for (name, algorithm) in names_algorithms {
    7552           24 :             test_random_updates_algorithm(name, algorithm).await?;
    7553           12 :         }
    7554           12 :         Ok(())
    7555           12 :     }
    7556              : 
    7557           24 :     async fn test_random_updates_algorithm(
    7558           24 :         name: &'static str,
    7559           24 :         compaction_algorithm: CompactionAlgorithm,
    7560           24 :     ) -> anyhow::Result<()> {
    7561           24 :         let mut harness = TenantHarness::create(name).await?;
    7562           24 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7563           24 :             kind: compaction_algorithm,
    7564           24 :         });
    7565           24 :         let (tenant, ctx) = harness.load().await;
    7566           24 :         let tline = tenant
    7567           24 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7568           24 :             .await?;
    7569              : 
    7570              :         const NUM_KEYS: usize = 1000;
    7571           24 :         let cancel = CancellationToken::new();
    7572           24 : 
    7573           24 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7574           24 :         let mut test_key_end = test_key;
    7575           24 :         test_key_end.field6 = NUM_KEYS as u32;
    7576           24 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7577           24 : 
    7578           24 :         let mut keyspace = KeySpaceAccum::new();
    7579           24 : 
    7580           24 :         // Track when each page was last modified. Used to assert that
    7581           24 :         // a read sees the latest page version.
    7582           24 :         let mut updated = [Lsn(0); NUM_KEYS];
    7583           24 : 
    7584           24 :         let mut lsn = Lsn(0x10);
    7585              :         #[allow(clippy::needless_range_loop)]
    7586        24024 :         for blknum in 0..NUM_KEYS {
    7587        24000 :             lsn = Lsn(lsn.0 + 0x10);
    7588        24000 :             test_key.field6 = blknum as u32;
    7589        24000 :             let mut writer = tline.writer().await;
    7590        24000 :             writer
    7591        24000 :                 .put(
    7592        24000 :                     test_key,
    7593        24000 :                     lsn,
    7594        24000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7595        24000 :                     &ctx,
    7596        24000 :                 )
    7597        24000 :                 .await?;
    7598        24000 :             writer.finish_write(lsn);
    7599        24000 :             updated[blknum] = lsn;
    7600        24000 :             drop(writer);
    7601        24000 : 
    7602        24000 :             keyspace.add_key(test_key);
    7603              :         }
    7604              : 
    7605         1224 :         for _ in 0..50 {
    7606      1201200 :             for _ in 0..NUM_KEYS {
    7607      1200000 :                 lsn = Lsn(lsn.0 + 0x10);
    7608      1200000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7609      1200000 :                 test_key.field6 = blknum as u32;
    7610      1200000 :                 let mut writer = tline.writer().await;
    7611      1200000 :                 writer
    7612      1200000 :                     .put(
    7613      1200000 :                         test_key,
    7614      1200000 :                         lsn,
    7615      1200000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7616      1200000 :                         &ctx,
    7617      1200000 :                     )
    7618      1200000 :                     .await?;
    7619      1200000 :                 writer.finish_write(lsn);
    7620      1200000 :                 drop(writer);
    7621      1200000 :                 updated[blknum] = lsn;
    7622              :             }
    7623              : 
    7624              :             // Read all the blocks
    7625      1200000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7626      1200000 :                 test_key.field6 = blknum as u32;
    7627      1200000 :                 assert_eq!(
    7628      1200000 :                     tline.get(test_key, lsn, &ctx).await?,
    7629      1200000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7630              :                 );
    7631              :             }
    7632              : 
    7633              :             // Perform a cycle of flush, and GC
    7634         1200 :             tline.freeze_and_flush().await?;
    7635         1200 :             tenant
    7636         1200 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7637         1200 :                 .await?;
    7638              :         }
    7639              : 
    7640           24 :         Ok(())
    7641           24 :     }
    7642              : 
    7643              :     #[tokio::test]
    7644           12 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7645           12 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7646           12 :             .await?
    7647           12 :             .load()
    7648           12 :             .await;
    7649           12 :         let mut tline = tenant
    7650           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7651           12 :             .await?;
    7652           12 : 
    7653           12 :         const NUM_KEYS: usize = 1000;
    7654           12 : 
    7655           12 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7656           12 : 
    7657           12 :         let mut keyspace = KeySpaceAccum::new();
    7658           12 : 
    7659           12 :         let cancel = CancellationToken::new();
    7660           12 : 
    7661           12 :         // Track when each page was last modified. Used to assert that
    7662           12 :         // a read sees the latest page version.
    7663           12 :         let mut updated = [Lsn(0); NUM_KEYS];
    7664           12 : 
    7665           12 :         let mut lsn = Lsn(0x10);
    7666           12 :         #[allow(clippy::needless_range_loop)]
    7667        12012 :         for blknum in 0..NUM_KEYS {
    7668        12000 :             lsn = Lsn(lsn.0 + 0x10);
    7669        12000 :             test_key.field6 = blknum as u32;
    7670        12000 :             let mut writer = tline.writer().await;
    7671        12000 :             writer
    7672        12000 :                 .put(
    7673        12000 :                     test_key,
    7674        12000 :                     lsn,
    7675        12000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7676        12000 :                     &ctx,
    7677        12000 :                 )
    7678        12000 :                 .await?;
    7679        12000 :             writer.finish_write(lsn);
    7680        12000 :             updated[blknum] = lsn;
    7681        12000 :             drop(writer);
    7682        12000 : 
    7683        12000 :             keyspace.add_key(test_key);
    7684           12 :         }
    7685           12 : 
    7686          612 :         for _ in 0..50 {
    7687          600 :             let new_tline_id = TimelineId::generate();
    7688          600 :             tenant
    7689          600 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7690          600 :                 .await?;
    7691          600 :             tline = tenant
    7692          600 :                 .get_timeline(new_tline_id, true)
    7693          600 :                 .expect("Should have the branched timeline");
    7694           12 : 
    7695       600600 :             for _ in 0..NUM_KEYS {
    7696       600000 :                 lsn = Lsn(lsn.0 + 0x10);
    7697       600000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7698       600000 :                 test_key.field6 = blknum as u32;
    7699       600000 :                 let mut writer = tline.writer().await;
    7700       600000 :                 writer
    7701       600000 :                     .put(
    7702       600000 :                         test_key,
    7703       600000 :                         lsn,
    7704       600000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7705       600000 :                         &ctx,
    7706       600000 :                     )
    7707       600000 :                     .await?;
    7708       600000 :                 println!("updating {} at {}", blknum, lsn);
    7709       600000 :                 writer.finish_write(lsn);
    7710       600000 :                 drop(writer);
    7711       600000 :                 updated[blknum] = lsn;
    7712           12 :             }
    7713           12 : 
    7714           12 :             // Read all the blocks
    7715       600000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7716       600000 :                 test_key.field6 = blknum as u32;
    7717       600000 :                 assert_eq!(
    7718       600000 :                     tline.get(test_key, lsn, &ctx).await?,
    7719       600000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    7720           12 :                 );
    7721           12 :             }
    7722           12 : 
    7723           12 :             // Perform a cycle of flush, compact, and GC
    7724          600 :             tline.freeze_and_flush().await?;
    7725          600 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7726          600 :             tenant
    7727          600 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7728          600 :                 .await?;
    7729           12 :         }
    7730           12 : 
    7731           12 :         Ok(())
    7732           12 :     }
    7733              : 
    7734              :     #[tokio::test]
    7735           12 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7736           12 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7737           12 :             .await?
    7738           12 :             .load()
    7739           12 :             .await;
    7740           12 :         let mut tline = tenant
    7741           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7742           12 :             .await?;
    7743           12 : 
    7744           12 :         const NUM_KEYS: usize = 100;
    7745           12 :         const NUM_TLINES: usize = 50;
    7746           12 : 
    7747           12 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7748           12 :         // Track page mutation lsns across different timelines.
    7749           12 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7750           12 : 
    7751           12 :         let mut lsn = Lsn(0x10);
    7752           12 : 
    7753           12 :         #[allow(clippy::needless_range_loop)]
    7754          612 :         for idx in 0..NUM_TLINES {
    7755          600 :             let new_tline_id = TimelineId::generate();
    7756          600 :             tenant
    7757          600 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7758          600 :                 .await?;
    7759          600 :             tline = tenant
    7760          600 :                 .get_timeline(new_tline_id, true)
    7761          600 :                 .expect("Should have the branched timeline");
    7762           12 : 
    7763        60600 :             for _ in 0..NUM_KEYS {
    7764        60000 :                 lsn = Lsn(lsn.0 + 0x10);
    7765        60000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7766        60000 :                 test_key.field6 = blknum as u32;
    7767        60000 :                 let mut writer = tline.writer().await;
    7768        60000 :                 writer
    7769        60000 :                     .put(
    7770        60000 :                         test_key,
    7771        60000 :                         lsn,
    7772        60000 :                         &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
    7773        60000 :                         &ctx,
    7774        60000 :                     )
    7775        60000 :                     .await?;
    7776        60000 :                 println!("updating [{}][{}] at {}", idx, blknum, lsn);
    7777        60000 :                 writer.finish_write(lsn);
    7778        60000 :                 drop(writer);
    7779        60000 :                 updated[idx][blknum] = lsn;
    7780           12 :             }
    7781           12 :         }
    7782           12 : 
    7783           12 :         // Read pages from leaf timeline across all ancestors.
    7784          600 :         for (idx, lsns) in updated.iter().enumerate() {
    7785        60000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7786           12 :                 // Skip empty mutations.
    7787        60000 :                 if lsn.0 == 0 {
    7788        21989 :                     continue;
    7789        38011 :                 }
    7790        38011 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7791        38011 :                 test_key.field6 = blknum as u32;
    7792        38011 :                 assert_eq!(
    7793        38011 :                     tline.get(test_key, *lsn, &ctx).await?,
    7794        38011 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7795           12 :                 );
    7796           12 :             }
    7797           12 :         }
    7798           12 :         Ok(())
    7799           12 :     }
    7800              : 
    7801              :     #[tokio::test]
    7802           12 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7803           12 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7804           12 :             .await?
    7805           12 :             .load()
    7806           12 :             .await;
    7807           12 : 
    7808           12 :         let initdb_lsn = Lsn(0x20);
    7809           12 :         let (utline, ctx) = tenant
    7810           12 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7811           12 :             .await?;
    7812           12 :         let tline = utline.raw_timeline().unwrap();
    7813           12 : 
    7814           12 :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7815           12 :         tline.maybe_spawn_flush_loop();
    7816           12 : 
    7817           12 :         // Make sure the timeline has the minimum set of required keys for operation.
    7818           12 :         // The only operation you can always do on an empty timeline is to `put` new data.
    7819           12 :         // Except if you `put` at `initdb_lsn`.
    7820           12 :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7821           12 :         // It uses `repartition()`, which assumes some keys to be present.
    7822           12 :         // Let's make sure the test timeline can handle that case.
    7823           12 :         {
    7824           12 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7825           12 :             assert_eq!(
    7826           12 :                 timeline::FlushLoopState::Running {
    7827           12 :                     expect_initdb_optimization: false,
    7828           12 :                     initdb_optimization_count: 0,
    7829           12 :                 },
    7830           12 :                 *state
    7831           12 :             );
    7832           12 :             *state = timeline::FlushLoopState::Running {
    7833           12 :                 expect_initdb_optimization: true,
    7834           12 :                 initdb_optimization_count: 0,
    7835           12 :             };
    7836           12 :         }
    7837           12 : 
    7838           12 :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    7839           12 :         // As explained above, the optimization requires some keys to be present.
    7840           12 :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    7841           12 :         // This is what `create_test_timeline` does, by the way.
    7842           12 :         let mut modification = tline.begin_modification(initdb_lsn);
    7843           12 :         modification
    7844           12 :             .init_empty_test_timeline()
    7845           12 :             .context("init_empty_test_timeline")?;
    7846           12 :         modification
    7847           12 :             .commit(&ctx)
    7848           12 :             .await
    7849           12 :             .context("commit init_empty_test_timeline modification")?;
    7850           12 : 
    7851           12 :         // Do the flush. The flush code will check the expectations that we set above.
    7852           12 :         tline.freeze_and_flush().await?;
    7853           12 : 
    7854           12 :         // assert freeze_and_flush exercised the initdb optimization
    7855           12 :         {
    7856           12 :             let state = tline.flush_loop_state.lock().unwrap();
    7857           12 :             let timeline::FlushLoopState::Running {
    7858           12 :                 expect_initdb_optimization,
    7859           12 :                 initdb_optimization_count,
    7860           12 :             } = *state
    7861           12 :             else {
    7862           12 :                 panic!("unexpected state: {:?}", *state);
    7863           12 :             };
    7864           12 :             assert!(expect_initdb_optimization);
    7865           12 :             assert!(initdb_optimization_count > 0);
    7866           12 :         }
    7867           12 :         Ok(())
    7868           12 :     }
    7869              : 
    7870              :     #[tokio::test]
    7871           12 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    7872           12 :         let name = "test_create_guard_crash";
    7873           12 :         let harness = TenantHarness::create(name).await?;
    7874           12 :         {
    7875           12 :             let (tenant, ctx) = harness.load().await;
    7876           12 :             let (tline, _ctx) = tenant
    7877           12 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7878           12 :                 .await?;
    7879           12 :             // Leave the timeline ID in [`TenantShard::timelines_creating`] to exclude attempting to create it again
    7880           12 :             let raw_tline = tline.raw_timeline().unwrap();
    7881           12 :             raw_tline
    7882           12 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    7883           12 :                 .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
    7884           12 :                 .await;
    7885           12 :             std::mem::forget(tline);
    7886           12 :         }
    7887           12 : 
    7888           12 :         let (tenant, _) = harness.load().await;
    7889           12 :         match tenant.get_timeline(TIMELINE_ID, false) {
    7890           12 :             Ok(_) => panic!("timeline should've been removed during load"),
    7891           12 :             Err(e) => {
    7892           12 :                 assert_eq!(
    7893           12 :                     e,
    7894           12 :                     GetTimelineError::NotFound {
    7895           12 :                         tenant_id: tenant.tenant_shard_id,
    7896           12 :                         timeline_id: TIMELINE_ID,
    7897           12 :                     }
    7898           12 :                 )
    7899           12 :             }
    7900           12 :         }
    7901           12 : 
    7902           12 :         assert!(
    7903           12 :             !harness
    7904           12 :                 .conf
    7905           12 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    7906           12 :                 .exists()
    7907           12 :         );
    7908           12 : 
    7909           12 :         Ok(())
    7910           12 :     }
    7911              : 
    7912              :     #[tokio::test]
    7913           12 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    7914           12 :         let names_algorithms = [
    7915           12 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    7916           12 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    7917           12 :         ];
    7918           36 :         for (name, algorithm) in names_algorithms {
    7919           24 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    7920           12 :         }
    7921           12 :         Ok(())
    7922           12 :     }
    7923              : 
    7924           24 :     async fn test_read_at_max_lsn_algorithm(
    7925           24 :         name: &'static str,
    7926           24 :         compaction_algorithm: CompactionAlgorithm,
    7927           24 :     ) -> anyhow::Result<()> {
    7928           24 :         let mut harness = TenantHarness::create(name).await?;
    7929           24 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7930           24 :             kind: compaction_algorithm,
    7931           24 :         });
    7932           24 :         let (tenant, ctx) = harness.load().await;
    7933           24 :         let tline = tenant
    7934           24 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7935           24 :             .await?;
    7936              : 
    7937           24 :         let lsn = Lsn(0x10);
    7938           24 :         let compact = false;
    7939           24 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    7940              : 
    7941           24 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7942           24 :         let read_lsn = Lsn(u64::MAX - 1);
    7943              : 
    7944           24 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    7945           24 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    7946              : 
    7947           24 :         Ok(())
    7948           24 :     }
    7949              : 
    7950              :     #[tokio::test]
    7951           12 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    7952           12 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    7953           12 :         let (tenant, ctx) = harness.load().await;
    7954           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7955           12 :         let tline = tenant
    7956           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7957           12 :             .await?;
    7958           12 : 
    7959           12 :         const NUM_KEYS: usize = 1000;
    7960           12 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    7961           12 : 
    7962           12 :         let cancel = CancellationToken::new();
    7963           12 : 
    7964           12 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    7965           12 :         base_key.field1 = AUX_KEY_PREFIX;
    7966           12 :         let mut test_key = base_key;
    7967           12 : 
    7968           12 :         // Track when each page was last modified. Used to assert that
    7969           12 :         // a read sees the latest page version.
    7970           12 :         let mut updated = [Lsn(0); NUM_KEYS];
    7971           12 : 
    7972           12 :         let mut lsn = Lsn(0x10);
    7973           12 :         #[allow(clippy::needless_range_loop)]
    7974        12012 :         for blknum in 0..NUM_KEYS {
    7975        12000 :             lsn = Lsn(lsn.0 + 0x10);
    7976        12000 :             test_key.field6 = (blknum * STEP) as u32;
    7977        12000 :             let mut writer = tline.writer().await;
    7978        12000 :             writer
    7979        12000 :                 .put(
    7980        12000 :                     test_key,
    7981        12000 :                     lsn,
    7982        12000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    7983        12000 :                     &ctx,
    7984        12000 :                 )
    7985        12000 :                 .await?;
    7986        12000 :             writer.finish_write(lsn);
    7987        12000 :             updated[blknum] = lsn;
    7988        12000 :             drop(writer);
    7989           12 :         }
    7990           12 : 
    7991           12 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    7992           12 : 
    7993          144 :         for iter in 0..=10 {
    7994           12 :             // Read all the blocks
    7995       132000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7996       132000 :                 test_key.field6 = (blknum * STEP) as u32;
    7997       132000 :                 assert_eq!(
    7998       132000 :                     tline.get(test_key, lsn, &ctx).await?,
    7999       132000 :                     test_img(&format!("{} at {}", blknum, last_lsn))
    8000           12 :                 );
    8001           12 :             }
    8002           12 : 
    8003          132 :             let mut cnt = 0;
    8004          132 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8005           12 : 
    8006       132000 :             for (key, value) in tline
    8007          132 :                 .get_vectored_impl(
    8008          132 :                     query,
    8009          132 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    8010          132 :                     &ctx,
    8011          132 :                 )
    8012          132 :                 .await?
    8013           12 :             {
    8014       132000 :                 let blknum = key.field6 as usize;
    8015       132000 :                 let value = value?;
    8016       132000 :                 assert!(blknum % STEP == 0);
    8017       132000 :                 let blknum = blknum / STEP;
    8018       132000 :                 assert_eq!(
    8019       132000 :                     value,
    8020       132000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8021       132000 :                 );
    8022       132000 :                 cnt += 1;
    8023           12 :             }
    8024           12 : 
    8025          132 :             assert_eq!(cnt, NUM_KEYS);
    8026           12 : 
    8027       132132 :             for _ in 0..NUM_KEYS {
    8028       132000 :                 lsn = Lsn(lsn.0 + 0x10);
    8029       132000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8030       132000 :                 test_key.field6 = (blknum * STEP) as u32;
    8031       132000 :                 let mut writer = tline.writer().await;
    8032       132000 :                 writer
    8033       132000 :                     .put(
    8034       132000 :                         test_key,
    8035       132000 :                         lsn,
    8036       132000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8037       132000 :                         &ctx,
    8038       132000 :                     )
    8039       132000 :                     .await?;
    8040       132000 :                 writer.finish_write(lsn);
    8041       132000 :                 drop(writer);
    8042       132000 :                 updated[blknum] = lsn;
    8043           12 :             }
    8044           12 : 
    8045           12 :             // Perform two cycles of flush, compact, and GC
    8046          396 :             for round in 0..2 {
    8047          264 :                 tline.freeze_and_flush().await?;
    8048          264 :                 tline
    8049          264 :                     .compact(
    8050          264 :                         &cancel,
    8051          264 :                         if iter % 5 == 0 && round == 0 {
    8052           36 :                             let mut flags = EnumSet::new();
    8053           36 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8054           36 :                             flags.insert(CompactFlags::ForceRepartition);
    8055           36 :                             flags
    8056           12 :                         } else {
    8057          228 :                             EnumSet::empty()
    8058           12 :                         },
    8059          264 :                         &ctx,
    8060          264 :                     )
    8061          264 :                     .await?;
    8062          264 :                 tenant
    8063          264 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8064          264 :                     .await?;
    8065           12 :             }
    8066           12 :         }
    8067           12 : 
    8068           12 :         Ok(())
    8069           12 :     }
    8070              : 
    8071              :     #[tokio::test]
    8072           12 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8073           12 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8074           12 :         let (tenant, ctx) = harness.load().await;
    8075           12 :         let tline = tenant
    8076           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8077           12 :             .await?;
    8078           12 : 
    8079           12 :         let cancel = CancellationToken::new();
    8080           12 : 
    8081           12 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8082           12 :         base_key.field1 = AUX_KEY_PREFIX;
    8083           12 :         let test_key = base_key;
    8084           12 :         let mut lsn = Lsn(0x10);
    8085           12 : 
    8086          252 :         for _ in 0..20 {
    8087          240 :             lsn = Lsn(lsn.0 + 0x10);
    8088          240 :             let mut writer = tline.writer().await;
    8089          240 :             writer
    8090          240 :                 .put(
    8091          240 :                     test_key,
    8092          240 :                     lsn,
    8093          240 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8094          240 :                     &ctx,
    8095          240 :                 )
    8096          240 :                 .await?;
    8097          240 :             writer.finish_write(lsn);
    8098          240 :             drop(writer);
    8099          240 :             tline.freeze_and_flush().await?; // force create a delta layer
    8100           12 :         }
    8101           12 : 
    8102           12 :         let before_num_l0_delta_files =
    8103           12 :             tline.layers.read().await.layer_map()?.level0_deltas().len();
    8104           12 : 
    8105           12 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8106           12 : 
    8107           12 :         let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
    8108           12 : 
    8109           12 :         assert!(
    8110           12 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8111           12 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8112           12 :         );
    8113           12 : 
    8114           12 :         assert_eq!(
    8115           12 :             tline.get(test_key, lsn, &ctx).await?,
    8116           12 :             test_img(&format!("{} at {}", 0, lsn))
    8117           12 :         );
    8118           12 : 
    8119           12 :         Ok(())
    8120           12 :     }
    8121              : 
    8122              :     #[tokio::test]
    8123           12 :     async fn test_aux_file_e2e() {
    8124           12 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8125           12 : 
    8126           12 :         let (tenant, ctx) = harness.load().await;
    8127           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8128           12 : 
    8129           12 :         let mut lsn = Lsn(0x08);
    8130           12 : 
    8131           12 :         let tline: Arc<Timeline> = tenant
    8132           12 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8133           12 :             .await
    8134           12 :             .unwrap();
    8135           12 : 
    8136           12 :         {
    8137           12 :             lsn += 8;
    8138           12 :             let mut modification = tline.begin_modification(lsn);
    8139           12 :             modification
    8140           12 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8141           12 :                 .await
    8142           12 :                 .unwrap();
    8143           12 :             modification.commit(&ctx).await.unwrap();
    8144           12 :         }
    8145           12 : 
    8146           12 :         // we can read everything from the storage
    8147           12 :         let files = tline
    8148           12 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8149           12 :             .await
    8150           12 :             .unwrap();
    8151           12 :         assert_eq!(
    8152           12 :             files.get("pg_logical/mappings/test1"),
    8153           12 :             Some(&bytes::Bytes::from_static(b"first"))
    8154           12 :         );
    8155           12 : 
    8156           12 :         {
    8157           12 :             lsn += 8;
    8158           12 :             let mut modification = tline.begin_modification(lsn);
    8159           12 :             modification
    8160           12 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8161           12 :                 .await
    8162           12 :                 .unwrap();
    8163           12 :             modification.commit(&ctx).await.unwrap();
    8164           12 :         }
    8165           12 : 
    8166           12 :         let files = tline
    8167           12 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8168           12 :             .await
    8169           12 :             .unwrap();
    8170           12 :         assert_eq!(
    8171           12 :             files.get("pg_logical/mappings/test2"),
    8172           12 :             Some(&bytes::Bytes::from_static(b"second"))
    8173           12 :         );
    8174           12 : 
    8175           12 :         let child = tenant
    8176           12 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8177           12 :             .await
    8178           12 :             .unwrap();
    8179           12 : 
    8180           12 :         let files = child
    8181           12 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8182           12 :             .await
    8183           12 :             .unwrap();
    8184           12 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8185           12 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8186           12 :     }
    8187              : 
    8188              :     #[tokio::test]
    8189           12 :     async fn test_repl_origin_tombstones() {
    8190           12 :         let harness = TenantHarness::create("test_repl_origin_tombstones")
    8191           12 :             .await
    8192           12 :             .unwrap();
    8193           12 : 
    8194           12 :         let (tenant, ctx) = harness.load().await;
    8195           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8196           12 : 
    8197           12 :         let mut lsn = Lsn(0x08);
    8198           12 : 
    8199           12 :         let tline: Arc<Timeline> = tenant
    8200           12 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8201           12 :             .await
    8202           12 :             .unwrap();
    8203           12 : 
    8204           12 :         let repl_lsn = Lsn(0x10);
    8205           12 :         {
    8206           12 :             lsn += 8;
    8207           12 :             let mut modification = tline.begin_modification(lsn);
    8208           12 :             modification.put_for_unit_test(repl_origin_key(2), Value::Image(Bytes::new()));
    8209           12 :             modification.set_replorigin(1, repl_lsn).await.unwrap();
    8210           12 :             modification.commit(&ctx).await.unwrap();
    8211           12 :         }
    8212           12 : 
    8213           12 :         // we can read everything from the storage
    8214           12 :         let repl_origins = tline
    8215           12 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8216           12 :             .await
    8217           12 :             .unwrap();
    8218           12 :         assert_eq!(repl_origins.len(), 1);
    8219           12 :         assert_eq!(repl_origins[&1], lsn);
    8220           12 : 
    8221           12 :         {
    8222           12 :             lsn += 8;
    8223           12 :             let mut modification = tline.begin_modification(lsn);
    8224           12 :             modification.put_for_unit_test(
    8225           12 :                 repl_origin_key(3),
    8226           12 :                 Value::Image(Bytes::copy_from_slice(b"cannot_decode_this")),
    8227           12 :             );
    8228           12 :             modification.commit(&ctx).await.unwrap();
    8229           12 :         }
    8230           12 :         let result = tline
    8231           12 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8232           12 :             .await;
    8233           12 :         assert!(result.is_err());
    8234           12 :     }
    8235              : 
    8236              :     #[tokio::test]
    8237           12 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8238           12 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8239           12 :         let (tenant, ctx) = harness.load().await;
    8240           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8241           12 :         let tline = tenant
    8242           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8243           12 :             .await?;
    8244           12 : 
    8245           12 :         const NUM_KEYS: usize = 1000;
    8246           12 :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8247           12 : 
    8248           12 :         let cancel = CancellationToken::new();
    8249           12 : 
    8250           12 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8251           12 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8252           12 :         let mut test_key = base_key;
    8253           12 :         let mut lsn = Lsn(0x10);
    8254           12 : 
    8255           48 :         async fn scan_with_statistics(
    8256           48 :             tline: &Timeline,
    8257           48 :             keyspace: &KeySpace,
    8258           48 :             lsn: Lsn,
    8259           48 :             ctx: &RequestContext,
    8260           48 :             io_concurrency: IoConcurrency,
    8261           48 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8262           48 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8263           48 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8264           48 :             let res = tline
    8265           48 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8266           48 :                 .await?;
    8267           48 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8268           48 :         }
    8269           12 : 
    8270        12012 :         for blknum in 0..NUM_KEYS {
    8271        12000 :             lsn = Lsn(lsn.0 + 0x10);
    8272        12000 :             test_key.field6 = (blknum * STEP) as u32;
    8273        12000 :             let mut writer = tline.writer().await;
    8274        12000 :             writer
    8275        12000 :                 .put(
    8276        12000 :                     test_key,
    8277        12000 :                     lsn,
    8278        12000 :                     &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8279        12000 :                     &ctx,
    8280        12000 :                 )
    8281        12000 :                 .await?;
    8282        12000 :             writer.finish_write(lsn);
    8283        12000 :             drop(writer);
    8284           12 :         }
    8285           12 : 
    8286           12 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8287           12 : 
    8288          132 :         for iter in 1..=10 {
    8289       120120 :             for _ in 0..NUM_KEYS {
    8290       120000 :                 lsn = Lsn(lsn.0 + 0x10);
    8291       120000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8292       120000 :                 test_key.field6 = (blknum * STEP) as u32;
    8293       120000 :                 let mut writer = tline.writer().await;
    8294       120000 :                 writer
    8295       120000 :                     .put(
    8296       120000 :                         test_key,
    8297       120000 :                         lsn,
    8298       120000 :                         &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
    8299       120000 :                         &ctx,
    8300       120000 :                     )
    8301       120000 :                     .await?;
    8302       120000 :                 writer.finish_write(lsn);
    8303       120000 :                 drop(writer);
    8304           12 :             }
    8305           12 : 
    8306          120 :             tline.freeze_and_flush().await?;
    8307           12 : 
    8308          120 :             if iter % 5 == 0 {
    8309           24 :                 let (_, before_delta_file_accessed) =
    8310           24 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    8311           24 :                         .await?;
    8312           24 :                 tline
    8313           24 :                     .compact(
    8314           24 :                         &cancel,
    8315           24 :                         {
    8316           24 :                             let mut flags = EnumSet::new();
    8317           24 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8318           24 :                             flags.insert(CompactFlags::ForceRepartition);
    8319           24 :                             flags
    8320           24 :                         },
    8321           24 :                         &ctx,
    8322           24 :                     )
    8323           24 :                     .await?;
    8324           24 :                 let (_, after_delta_file_accessed) =
    8325           24 :                     scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
    8326           24 :                         .await?;
    8327           24 :                 assert!(
    8328           24 :                     after_delta_file_accessed < before_delta_file_accessed,
    8329           12 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8330           12 :                 );
    8331           12 :                 // Given that we already produced an image layer, there should be no delta layer needed for the scan, but still setting a low threshold there for unforeseen circumstances.
    8332           24 :                 assert!(
    8333           24 :                     after_delta_file_accessed <= 2,
    8334           12 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8335           12 :                 );
    8336           96 :             }
    8337           12 :         }
    8338           12 : 
    8339           12 :         Ok(())
    8340           12 :     }
    8341              : 
    8342              :     #[tokio::test]
    8343           12 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8344           12 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8345           12 :         let (tenant, ctx) = harness.load().await;
    8346           12 : 
    8347           12 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8348           12 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8349           12 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8350           12 : 
    8351           12 :         let tline = tenant
    8352           12 :             .create_test_timeline_with_layers(
    8353           12 :                 TIMELINE_ID,
    8354           12 :                 Lsn(0x10),
    8355           12 :                 DEFAULT_PG_VERSION,
    8356           12 :                 &ctx,
    8357           12 :                 Vec::new(), // in-memory layers
    8358           12 :                 Vec::new(), // delta layers
    8359           12 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8360           12 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    8361           12 :             )
    8362           12 :             .await?;
    8363           12 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8364           12 : 
    8365           12 :         let child = tenant
    8366           12 :             .branch_timeline_test_with_layers(
    8367           12 :                 &tline,
    8368           12 :                 NEW_TIMELINE_ID,
    8369           12 :                 Some(Lsn(0x20)),
    8370           12 :                 &ctx,
    8371           12 :                 Vec::new(), // delta layers
    8372           12 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8373           12 :                 Lsn(0x30),
    8374           12 :             )
    8375           12 :             .await
    8376           12 :             .unwrap();
    8377           12 : 
    8378           12 :         let lsn = Lsn(0x30);
    8379           12 : 
    8380           12 :         // test vectored get on parent timeline
    8381           12 :         assert_eq!(
    8382           12 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8383           12 :             Some(test_img("data key 1"))
    8384           12 :         );
    8385           12 :         assert!(
    8386           12 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8387           12 :                 .await
    8388           12 :                 .unwrap_err()
    8389           12 :                 .is_missing_key_error()
    8390           12 :         );
    8391           12 :         assert!(
    8392           12 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8393           12 :                 .await
    8394           12 :                 .unwrap_err()
    8395           12 :                 .is_missing_key_error()
    8396           12 :         );
    8397           12 : 
    8398           12 :         // test vectored get on child timeline
    8399           12 :         assert_eq!(
    8400           12 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8401           12 :             Some(test_img("data key 1"))
    8402           12 :         );
    8403           12 :         assert_eq!(
    8404           12 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8405           12 :             Some(test_img("data key 2"))
    8406           12 :         );
    8407           12 :         assert!(
    8408           12 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8409           12 :                 .await
    8410           12 :                 .unwrap_err()
    8411           12 :                 .is_missing_key_error()
    8412           12 :         );
    8413           12 : 
    8414           12 :         Ok(())
    8415           12 :     }
    8416              : 
    8417              :     #[tokio::test]
    8418           12 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8419           12 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8420           12 :         let (tenant, ctx) = harness.load().await;
    8421           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8422           12 : 
    8423           12 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8424           12 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8425           12 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8426           12 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8427           12 : 
    8428           12 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8429           12 :         let base_inherited_key_child =
    8430           12 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8431           12 :         let base_inherited_key_nonexist =
    8432           12 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8433           12 :         let base_inherited_key_overwrite =
    8434           12 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8435           12 : 
    8436           12 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8437           12 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8438           12 : 
    8439           12 :         let tline = tenant
    8440           12 :             .create_test_timeline_with_layers(
    8441           12 :                 TIMELINE_ID,
    8442           12 :                 Lsn(0x10),
    8443           12 :                 DEFAULT_PG_VERSION,
    8444           12 :                 &ctx,
    8445           12 :                 Vec::new(), // in-memory layers
    8446           12 :                 Vec::new(), // delta layers
    8447           12 :                 vec![(
    8448           12 :                     Lsn(0x20),
    8449           12 :                     vec![
    8450           12 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8451           12 :                         (
    8452           12 :                             base_inherited_key_overwrite,
    8453           12 :                             test_img("metadata key overwrite 1a"),
    8454           12 :                         ),
    8455           12 :                         (base_key, test_img("metadata key 1")),
    8456           12 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8457           12 :                     ],
    8458           12 :                 )], // image layers
    8459           12 :                 Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
    8460           12 :             )
    8461           12 :             .await?;
    8462           12 : 
    8463           12 :         let child = tenant
    8464           12 :             .branch_timeline_test_with_layers(
    8465           12 :                 &tline,
    8466           12 :                 NEW_TIMELINE_ID,
    8467           12 :                 Some(Lsn(0x20)),
    8468           12 :                 &ctx,
    8469           12 :                 Vec::new(), // delta layers
    8470           12 :                 vec![(
    8471           12 :                     Lsn(0x30),
    8472           12 :                     vec![
    8473           12 :                         (
    8474           12 :                             base_inherited_key_child,
    8475           12 :                             test_img("metadata inherited key 2"),
    8476           12 :                         ),
    8477           12 :                         (
    8478           12 :                             base_inherited_key_overwrite,
    8479           12 :                             test_img("metadata key overwrite 2a"),
    8480           12 :                         ),
    8481           12 :                         (base_key_child, test_img("metadata key 2")),
    8482           12 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8483           12 :                     ],
    8484           12 :                 )], // image layers
    8485           12 :                 Lsn(0x30),
    8486           12 :             )
    8487           12 :             .await
    8488           12 :             .unwrap();
    8489           12 : 
    8490           12 :         let lsn = Lsn(0x30);
    8491           12 : 
    8492           12 :         // test vectored get on parent timeline
    8493           12 :         assert_eq!(
    8494           12 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8495           12 :             Some(test_img("metadata key 1"))
    8496           12 :         );
    8497           12 :         assert_eq!(
    8498           12 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8499           12 :             None
    8500           12 :         );
    8501           12 :         assert_eq!(
    8502           12 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8503           12 :             None
    8504           12 :         );
    8505           12 :         assert_eq!(
    8506           12 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8507           12 :             Some(test_img("metadata key overwrite 1b"))
    8508           12 :         );
    8509           12 :         assert_eq!(
    8510           12 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8511           12 :             Some(test_img("metadata inherited key 1"))
    8512           12 :         );
    8513           12 :         assert_eq!(
    8514           12 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8515           12 :             None
    8516           12 :         );
    8517           12 :         assert_eq!(
    8518           12 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8519           12 :             None
    8520           12 :         );
    8521           12 :         assert_eq!(
    8522           12 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8523           12 :             Some(test_img("metadata key overwrite 1a"))
    8524           12 :         );
    8525           12 : 
    8526           12 :         // test vectored get on child timeline
    8527           12 :         assert_eq!(
    8528           12 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8529           12 :             None
    8530           12 :         );
    8531           12 :         assert_eq!(
    8532           12 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8533           12 :             Some(test_img("metadata key 2"))
    8534           12 :         );
    8535           12 :         assert_eq!(
    8536           12 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8537           12 :             None
    8538           12 :         );
    8539           12 :         assert_eq!(
    8540           12 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8541           12 :             Some(test_img("metadata inherited key 1"))
    8542           12 :         );
    8543           12 :         assert_eq!(
    8544           12 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8545           12 :             Some(test_img("metadata inherited key 2"))
    8546           12 :         );
    8547           12 :         assert_eq!(
    8548           12 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8549           12 :             None
    8550           12 :         );
    8551           12 :         assert_eq!(
    8552           12 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8553           12 :             Some(test_img("metadata key overwrite 2b"))
    8554           12 :         );
    8555           12 :         assert_eq!(
    8556           12 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8557           12 :             Some(test_img("metadata key overwrite 2a"))
    8558           12 :         );
    8559           12 : 
    8560           12 :         // test vectored scan on parent timeline
    8561           12 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8562           12 :         let query =
    8563           12 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8564           12 :         let res = tline
    8565           12 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8566           12 :             .await?;
    8567           12 : 
    8568           12 :         assert_eq!(
    8569           12 :             res.into_iter()
    8570           48 :                 .map(|(k, v)| (k, v.unwrap()))
    8571           12 :                 .collect::<Vec<_>>(),
    8572           12 :             vec![
    8573           12 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8574           12 :                 (
    8575           12 :                     base_inherited_key_overwrite,
    8576           12 :                     test_img("metadata key overwrite 1a")
    8577           12 :                 ),
    8578           12 :                 (base_key, test_img("metadata key 1")),
    8579           12 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8580           12 :             ]
    8581           12 :         );
    8582           12 : 
    8583           12 :         // test vectored scan on child timeline
    8584           12 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8585           12 :         let query =
    8586           12 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8587           12 :         let res = child
    8588           12 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8589           12 :             .await?;
    8590           12 : 
    8591           12 :         assert_eq!(
    8592           12 :             res.into_iter()
    8593           60 :                 .map(|(k, v)| (k, v.unwrap()))
    8594           12 :                 .collect::<Vec<_>>(),
    8595           12 :             vec![
    8596           12 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8597           12 :                 (
    8598           12 :                     base_inherited_key_child,
    8599           12 :                     test_img("metadata inherited key 2")
    8600           12 :                 ),
    8601           12 :                 (
    8602           12 :                     base_inherited_key_overwrite,
    8603           12 :                     test_img("metadata key overwrite 2a")
    8604           12 :                 ),
    8605           12 :                 (base_key_child, test_img("metadata key 2")),
    8606           12 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8607           12 :             ]
    8608           12 :         );
    8609           12 : 
    8610           12 :         Ok(())
    8611           12 :     }
    8612              : 
    8613          336 :     async fn get_vectored_impl_wrapper(
    8614          336 :         tline: &Arc<Timeline>,
    8615          336 :         key: Key,
    8616          336 :         lsn: Lsn,
    8617          336 :         ctx: &RequestContext,
    8618          336 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8619          336 :         let io_concurrency =
    8620          336 :             IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
    8621          336 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8622          336 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8623          336 :         let mut res = tline
    8624          336 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8625          336 :             .await?;
    8626          300 :         Ok(res.pop_last().map(|(k, v)| {
    8627          192 :             assert_eq!(k, key);
    8628          192 :             v.unwrap()
    8629          300 :         }))
    8630          336 :     }
    8631              : 
    8632              :     #[tokio::test]
    8633           12 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8634           12 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8635           12 :         let (tenant, ctx) = harness.load().await;
    8636           12 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8637           12 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8638           12 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8639           12 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8640           12 : 
    8641           12 :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8642           12 :         // Lsn 0x30 key0, key3, no key1+key2
    8643           12 :         // Lsn 0x20 key1+key2 tomestones
    8644           12 :         // Lsn 0x10 key1 in image, key2 in delta
    8645           12 :         let tline = tenant
    8646           12 :             .create_test_timeline_with_layers(
    8647           12 :                 TIMELINE_ID,
    8648           12 :                 Lsn(0x10),
    8649           12 :                 DEFAULT_PG_VERSION,
    8650           12 :                 &ctx,
    8651           12 :                 Vec::new(), // in-memory layers
    8652           12 :                 // delta layers
    8653           12 :                 vec![
    8654           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8655           12 :                         Lsn(0x10)..Lsn(0x20),
    8656           12 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8657           12 :                     ),
    8658           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8659           12 :                         Lsn(0x20)..Lsn(0x30),
    8660           12 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8661           12 :                     ),
    8662           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8663           12 :                         Lsn(0x20)..Lsn(0x30),
    8664           12 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8665           12 :                     ),
    8666           12 :                 ],
    8667           12 :                 // image layers
    8668           12 :                 vec![
    8669           12 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8670           12 :                     (
    8671           12 :                         Lsn(0x30),
    8672           12 :                         vec![
    8673           12 :                             (key0, test_img("metadata key 0")),
    8674           12 :                             (key3, test_img("metadata key 3")),
    8675           12 :                         ],
    8676           12 :                     ),
    8677           12 :                 ],
    8678           12 :                 Lsn(0x30),
    8679           12 :             )
    8680           12 :             .await?;
    8681           12 : 
    8682           12 :         let lsn = Lsn(0x30);
    8683           12 :         let old_lsn = Lsn(0x20);
    8684           12 : 
    8685           12 :         assert_eq!(
    8686           12 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8687           12 :             Some(test_img("metadata key 0"))
    8688           12 :         );
    8689           12 :         assert_eq!(
    8690           12 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8691           12 :             None,
    8692           12 :         );
    8693           12 :         assert_eq!(
    8694           12 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8695           12 :             None,
    8696           12 :         );
    8697           12 :         assert_eq!(
    8698           12 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8699           12 :             Some(Bytes::new()),
    8700           12 :         );
    8701           12 :         assert_eq!(
    8702           12 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8703           12 :             Some(Bytes::new()),
    8704           12 :         );
    8705           12 :         assert_eq!(
    8706           12 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8707           12 :             Some(test_img("metadata key 3"))
    8708           12 :         );
    8709           12 : 
    8710           12 :         Ok(())
    8711           12 :     }
    8712              : 
    8713              :     #[tokio::test]
    8714           12 :     async fn test_metadata_tombstone_image_creation() {
    8715           12 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8716           12 :             .await
    8717           12 :             .unwrap();
    8718           12 :         let (tenant, ctx) = harness.load().await;
    8719           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8720           12 : 
    8721           12 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8722           12 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8723           12 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8724           12 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8725           12 : 
    8726           12 :         let tline = tenant
    8727           12 :             .create_test_timeline_with_layers(
    8728           12 :                 TIMELINE_ID,
    8729           12 :                 Lsn(0x10),
    8730           12 :                 DEFAULT_PG_VERSION,
    8731           12 :                 &ctx,
    8732           12 :                 Vec::new(), // in-memory layers
    8733           12 :                 // delta layers
    8734           12 :                 vec![
    8735           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8736           12 :                         Lsn(0x10)..Lsn(0x20),
    8737           12 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8738           12 :                     ),
    8739           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8740           12 :                         Lsn(0x20)..Lsn(0x30),
    8741           12 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8742           12 :                     ),
    8743           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8744           12 :                         Lsn(0x20)..Lsn(0x30),
    8745           12 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8746           12 :                     ),
    8747           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8748           12 :                         Lsn(0x30)..Lsn(0x40),
    8749           12 :                         vec![
    8750           12 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8751           12 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8752           12 :                         ],
    8753           12 :                     ),
    8754           12 :                 ],
    8755           12 :                 // image layers
    8756           12 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8757           12 :                 Lsn(0x40),
    8758           12 :             )
    8759           12 :             .await
    8760           12 :             .unwrap();
    8761           12 : 
    8762           12 :         let cancel = CancellationToken::new();
    8763           12 : 
    8764           12 :         tline
    8765           12 :             .compact(
    8766           12 :                 &cancel,
    8767           12 :                 {
    8768           12 :                     let mut flags = EnumSet::new();
    8769           12 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8770           12 :                     flags.insert(CompactFlags::ForceRepartition);
    8771           12 :                     flags
    8772           12 :                 },
    8773           12 :                 &ctx,
    8774           12 :             )
    8775           12 :             .await
    8776           12 :             .unwrap();
    8777           12 : 
    8778           12 :         // Image layers are created at last_record_lsn
    8779           12 :         let images = tline
    8780           12 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8781           12 :             .await
    8782           12 :             .unwrap()
    8783           12 :             .into_iter()
    8784          108 :             .filter(|(k, _)| k.is_metadata_key())
    8785           12 :             .collect::<Vec<_>>();
    8786           12 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8787           12 :     }
    8788              : 
    8789              :     #[tokio::test]
    8790           12 :     async fn test_metadata_tombstone_empty_image_creation() {
    8791           12 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8792           12 :             .await
    8793           12 :             .unwrap();
    8794           12 :         let (tenant, ctx) = harness.load().await;
    8795           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8796           12 : 
    8797           12 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8798           12 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8799           12 : 
    8800           12 :         let tline = tenant
    8801           12 :             .create_test_timeline_with_layers(
    8802           12 :                 TIMELINE_ID,
    8803           12 :                 Lsn(0x10),
    8804           12 :                 DEFAULT_PG_VERSION,
    8805           12 :                 &ctx,
    8806           12 :                 Vec::new(), // in-memory layers
    8807           12 :                 // delta layers
    8808           12 :                 vec![
    8809           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8810           12 :                         Lsn(0x10)..Lsn(0x20),
    8811           12 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8812           12 :                     ),
    8813           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8814           12 :                         Lsn(0x20)..Lsn(0x30),
    8815           12 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8816           12 :                     ),
    8817           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8818           12 :                         Lsn(0x20)..Lsn(0x30),
    8819           12 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8820           12 :                     ),
    8821           12 :                 ],
    8822           12 :                 // image layers
    8823           12 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8824           12 :                 Lsn(0x30),
    8825           12 :             )
    8826           12 :             .await
    8827           12 :             .unwrap();
    8828           12 : 
    8829           12 :         let cancel = CancellationToken::new();
    8830           12 : 
    8831           12 :         tline
    8832           12 :             .compact(
    8833           12 :                 &cancel,
    8834           12 :                 {
    8835           12 :                     let mut flags = EnumSet::new();
    8836           12 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8837           12 :                     flags.insert(CompactFlags::ForceRepartition);
    8838           12 :                     flags
    8839           12 :                 },
    8840           12 :                 &ctx,
    8841           12 :             )
    8842           12 :             .await
    8843           12 :             .unwrap();
    8844           12 : 
    8845           12 :         // Image layers are created at last_record_lsn
    8846           12 :         let images = tline
    8847           12 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    8848           12 :             .await
    8849           12 :             .unwrap()
    8850           12 :             .into_iter()
    8851           84 :             .filter(|(k, _)| k.is_metadata_key())
    8852           12 :             .collect::<Vec<_>>();
    8853           12 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    8854           12 :     }
    8855              : 
    8856              :     #[tokio::test]
    8857           12 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    8858           12 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    8859           12 :         let (tenant, ctx) = harness.load().await;
    8860           12 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8861           12 : 
    8862          612 :         fn get_key(id: u32) -> Key {
    8863          612 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    8864          612 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8865          612 :             key.field6 = id;
    8866          612 :             key
    8867          612 :         }
    8868           12 : 
    8869           12 :         // We create
    8870           12 :         // - one bottom-most image layer,
    8871           12 :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    8872           12 :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    8873           12 :         // - a delta layer D3 above the horizon.
    8874           12 :         //
    8875           12 :         //                             | D3 |
    8876           12 :         //  | D1 |
    8877           12 :         // -|    |-- gc horizon -----------------
    8878           12 :         //  |    |                | D2 |
    8879           12 :         // --------- img layer ------------------
    8880           12 :         //
    8881           12 :         // What we should expact from this compaction is:
    8882           12 :         //                             | D3 |
    8883           12 :         //  | Part of D1 |
    8884           12 :         // --------- img layer with D1+D2 at GC horizon------------------
    8885           12 : 
    8886           12 :         // img layer at 0x10
    8887           12 :         let img_layer = (0..10)
    8888          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    8889           12 :             .collect_vec();
    8890           12 : 
    8891           12 :         let delta1 = vec![
    8892           12 :             (
    8893           12 :                 get_key(1),
    8894           12 :                 Lsn(0x20),
    8895           12 :                 Value::Image(Bytes::from("value 1@0x20")),
    8896           12 :             ),
    8897           12 :             (
    8898           12 :                 get_key(2),
    8899           12 :                 Lsn(0x30),
    8900           12 :                 Value::Image(Bytes::from("value 2@0x30")),
    8901           12 :             ),
    8902           12 :             (
    8903           12 :                 get_key(3),
    8904           12 :                 Lsn(0x40),
    8905           12 :                 Value::Image(Bytes::from("value 3@0x40")),
    8906           12 :             ),
    8907           12 :         ];
    8908           12 :         let delta2 = vec![
    8909           12 :             (
    8910           12 :                 get_key(5),
    8911           12 :                 Lsn(0x20),
    8912           12 :                 Value::Image(Bytes::from("value 5@0x20")),
    8913           12 :             ),
    8914           12 :             (
    8915           12 :                 get_key(6),
    8916           12 :                 Lsn(0x20),
    8917           12 :                 Value::Image(Bytes::from("value 6@0x20")),
    8918           12 :             ),
    8919           12 :         ];
    8920           12 :         let delta3 = vec![
    8921           12 :             (
    8922           12 :                 get_key(8),
    8923           12 :                 Lsn(0x48),
    8924           12 :                 Value::Image(Bytes::from("value 8@0x48")),
    8925           12 :             ),
    8926           12 :             (
    8927           12 :                 get_key(9),
    8928           12 :                 Lsn(0x48),
    8929           12 :                 Value::Image(Bytes::from("value 9@0x48")),
    8930           12 :             ),
    8931           12 :         ];
    8932           12 : 
    8933           12 :         let tline = tenant
    8934           12 :             .create_test_timeline_with_layers(
    8935           12 :                 TIMELINE_ID,
    8936           12 :                 Lsn(0x10),
    8937           12 :                 DEFAULT_PG_VERSION,
    8938           12 :                 &ctx,
    8939           12 :                 Vec::new(), // in-memory layers
    8940           12 :                 vec![
    8941           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    8942           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    8943           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    8944           12 :                 ], // delta layers
    8945           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
    8946           12 :                 Lsn(0x50),
    8947           12 :             )
    8948           12 :             .await?;
    8949           12 :         {
    8950           12 :             tline
    8951           12 :                 .applied_gc_cutoff_lsn
    8952           12 :                 .lock_for_write()
    8953           12 :                 .store_and_unlock(Lsn(0x30))
    8954           12 :                 .wait()
    8955           12 :                 .await;
    8956           12 :             // Update GC info
    8957           12 :             let mut guard = tline.gc_info.write().unwrap();
    8958           12 :             guard.cutoffs.time = Lsn(0x30);
    8959           12 :             guard.cutoffs.space = Lsn(0x30);
    8960           12 :         }
    8961           12 : 
    8962           12 :         let expected_result = [
    8963           12 :             Bytes::from_static(b"value 0@0x10"),
    8964           12 :             Bytes::from_static(b"value 1@0x20"),
    8965           12 :             Bytes::from_static(b"value 2@0x30"),
    8966           12 :             Bytes::from_static(b"value 3@0x40"),
    8967           12 :             Bytes::from_static(b"value 4@0x10"),
    8968           12 :             Bytes::from_static(b"value 5@0x20"),
    8969           12 :             Bytes::from_static(b"value 6@0x20"),
    8970           12 :             Bytes::from_static(b"value 7@0x10"),
    8971           12 :             Bytes::from_static(b"value 8@0x48"),
    8972           12 :             Bytes::from_static(b"value 9@0x48"),
    8973           12 :         ];
    8974           12 : 
    8975          120 :         for (idx, expected) in expected_result.iter().enumerate() {
    8976          120 :             assert_eq!(
    8977          120 :                 tline
    8978          120 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8979          120 :                     .await
    8980          120 :                     .unwrap(),
    8981           12 :                 expected
    8982           12 :             );
    8983           12 :         }
    8984           12 : 
    8985           12 :         let cancel = CancellationToken::new();
    8986           12 :         tline
    8987           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    8988           12 :             .await
    8989           12 :             .unwrap();
    8990           12 : 
    8991          120 :         for (idx, expected) in expected_result.iter().enumerate() {
    8992          120 :             assert_eq!(
    8993          120 :                 tline
    8994          120 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    8995          120 :                     .await
    8996          120 :                     .unwrap(),
    8997           12 :                 expected
    8998           12 :             );
    8999           12 :         }
    9000           12 : 
    9001           12 :         // Check if the image layer at the GC horizon contains exactly what we want
    9002           12 :         let image_at_gc_horizon = tline
    9003           12 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9004           12 :             .await
    9005           12 :             .unwrap()
    9006           12 :             .into_iter()
    9007          204 :             .filter(|(k, _)| k.is_metadata_key())
    9008           12 :             .collect::<Vec<_>>();
    9009           12 : 
    9010           12 :         assert_eq!(image_at_gc_horizon.len(), 10);
    9011           12 :         let expected_result = [
    9012           12 :             Bytes::from_static(b"value 0@0x10"),
    9013           12 :             Bytes::from_static(b"value 1@0x20"),
    9014           12 :             Bytes::from_static(b"value 2@0x30"),
    9015           12 :             Bytes::from_static(b"value 3@0x10"),
    9016           12 :             Bytes::from_static(b"value 4@0x10"),
    9017           12 :             Bytes::from_static(b"value 5@0x20"),
    9018           12 :             Bytes::from_static(b"value 6@0x20"),
    9019           12 :             Bytes::from_static(b"value 7@0x10"),
    9020           12 :             Bytes::from_static(b"value 8@0x10"),
    9021           12 :             Bytes::from_static(b"value 9@0x10"),
    9022           12 :         ];
    9023          132 :         for idx in 0..10 {
    9024          120 :             assert_eq!(
    9025          120 :                 image_at_gc_horizon[idx],
    9026          120 :                 (get_key(idx as u32), expected_result[idx].clone())
    9027          120 :             );
    9028           12 :         }
    9029           12 : 
    9030           12 :         // Check if old layers are removed / new layers have the expected LSN
    9031           12 :         let all_layers = inspect_and_sort(&tline, None).await;
    9032           12 :         assert_eq!(
    9033           12 :             all_layers,
    9034           12 :             vec![
    9035           12 :                 // Image layer at GC horizon
    9036           12 :                 PersistentLayerKey {
    9037           12 :                     key_range: Key::MIN..Key::MAX,
    9038           12 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    9039           12 :                     is_delta: false
    9040           12 :                 },
    9041           12 :                 // The delta layer below the horizon
    9042           12 :                 PersistentLayerKey {
    9043           12 :                     key_range: get_key(3)..get_key(4),
    9044           12 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    9045           12 :                     is_delta: true
    9046           12 :                 },
    9047           12 :                 // The delta3 layer that should not be picked for the compaction
    9048           12 :                 PersistentLayerKey {
    9049           12 :                     key_range: get_key(8)..get_key(10),
    9050           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9051           12 :                     is_delta: true
    9052           12 :                 }
    9053           12 :             ]
    9054           12 :         );
    9055           12 : 
    9056           12 :         // increase GC horizon and compact again
    9057           12 :         {
    9058           12 :             tline
    9059           12 :                 .applied_gc_cutoff_lsn
    9060           12 :                 .lock_for_write()
    9061           12 :                 .store_and_unlock(Lsn(0x40))
    9062           12 :                 .wait()
    9063           12 :                 .await;
    9064           12 :             // Update GC info
    9065           12 :             let mut guard = tline.gc_info.write().unwrap();
    9066           12 :             guard.cutoffs.time = Lsn(0x40);
    9067           12 :             guard.cutoffs.space = Lsn(0x40);
    9068           12 :         }
    9069           12 :         tline
    9070           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9071           12 :             .await
    9072           12 :             .unwrap();
    9073           12 : 
    9074           12 :         Ok(())
    9075           12 :     }
    9076              : 
    9077              :     #[cfg(feature = "testing")]
    9078              :     #[tokio::test]
    9079           12 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9080           12 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9081           12 :         let (tenant, ctx) = harness.load().await;
    9082           12 : 
    9083          204 :         fn get_key(id: u32) -> Key {
    9084          204 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9085          204 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9086          204 :             key.field6 = id;
    9087          204 :             key
    9088          204 :         }
    9089           12 : 
    9090           12 :         let delta1 = vec![
    9091           12 :             (
    9092           12 :                 get_key(1),
    9093           12 :                 Lsn(0x20),
    9094           12 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9095           12 :             ),
    9096           12 :             (
    9097           12 :                 get_key(1),
    9098           12 :                 Lsn(0x30),
    9099           12 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9100           12 :             ),
    9101           12 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9102           12 :             (
    9103           12 :                 get_key(2),
    9104           12 :                 Lsn(0x20),
    9105           12 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9106           12 :             ),
    9107           12 :             (
    9108           12 :                 get_key(2),
    9109           12 :                 Lsn(0x30),
    9110           12 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9111           12 :             ),
    9112           12 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9113           12 :             (
    9114           12 :                 get_key(3),
    9115           12 :                 Lsn(0x20),
    9116           12 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9117           12 :             ),
    9118           12 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9119           12 :             (
    9120           12 :                 get_key(4),
    9121           12 :                 Lsn(0x20),
    9122           12 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9123           12 :             ),
    9124           12 :             (
    9125           12 :                 get_key(4),
    9126           12 :                 Lsn(0x30),
    9127           12 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9128           12 :             ),
    9129           12 :             (
    9130           12 :                 get_key(5),
    9131           12 :                 Lsn(0x20),
    9132           12 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9133           12 :             ),
    9134           12 :             (
    9135           12 :                 get_key(5),
    9136           12 :                 Lsn(0x30),
    9137           12 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9138           12 :             ),
    9139           12 :         ];
    9140           12 :         let image1 = vec![(get_key(1), "0x10".into())];
    9141           12 : 
    9142           12 :         let tline = tenant
    9143           12 :             .create_test_timeline_with_layers(
    9144           12 :                 TIMELINE_ID,
    9145           12 :                 Lsn(0x10),
    9146           12 :                 DEFAULT_PG_VERSION,
    9147           12 :                 &ctx,
    9148           12 :                 Vec::new(), // in-memory layers
    9149           12 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9150           12 :                     Lsn(0x10)..Lsn(0x40),
    9151           12 :                     delta1,
    9152           12 :                 )], // delta layers
    9153           12 :                 vec![(Lsn(0x10), image1)], // image layers
    9154           12 :                 Lsn(0x50),
    9155           12 :             )
    9156           12 :             .await?;
    9157           12 : 
    9158           12 :         assert_eq!(
    9159           12 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9160           12 :             Bytes::from_static(b"0x10,0x20,0x30")
    9161           12 :         );
    9162           12 :         assert_eq!(
    9163           12 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9164           12 :             Bytes::from_static(b"0x10,0x20,0x30")
    9165           12 :         );
    9166           12 : 
    9167           12 :         // Need to remove the limit of "Neon WAL redo requires base image".
    9168           12 : 
    9169           12 :         assert_eq!(
    9170           12 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9171           12 :             Bytes::from_static(b"c")
    9172           12 :         );
    9173           12 :         assert_eq!(
    9174           12 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9175           12 :             Bytes::from_static(b"ij")
    9176           12 :         );
    9177           12 : 
    9178           12 :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9179           12 :         // cannot enable this assertion in the unit test.
    9180           12 :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9181           12 : 
    9182           12 :         Ok(())
    9183           12 :     }
    9184              : 
    9185              :     #[tokio::test(start_paused = true)]
    9186           12 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9187           12 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9188           12 :             .await
    9189           12 :             .unwrap()
    9190           12 :             .load()
    9191           12 :             .await;
    9192           12 :         // Advance to the lsn lease deadline so that GC is not blocked by
    9193           12 :         // initial transition into AttachedSingle.
    9194           12 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    9195           12 :         tokio::time::resume();
    9196           12 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9197           12 : 
    9198           12 :         let end_lsn = Lsn(0x100);
    9199           12 :         let image_layers = (0x20..=0x90)
    9200           12 :             .step_by(0x10)
    9201           96 :             .map(|n| {
    9202           96 :                 (
    9203           96 :                     Lsn(n),
    9204           96 :                     vec![(key, test_img(&format!("data key at {:x}", n)))],
    9205           96 :                 )
    9206           96 :             })
    9207           12 :             .collect();
    9208           12 : 
    9209           12 :         let timeline = tenant
    9210           12 :             .create_test_timeline_with_layers(
    9211           12 :                 TIMELINE_ID,
    9212           12 :                 Lsn(0x10),
    9213           12 :                 DEFAULT_PG_VERSION,
    9214           12 :                 &ctx,
    9215           12 :                 Vec::new(), // in-memory layers
    9216           12 :                 Vec::new(),
    9217           12 :                 image_layers,
    9218           12 :                 end_lsn,
    9219           12 :             )
    9220           12 :             .await?;
    9221           12 : 
    9222           12 :         let leased_lsns = [0x30, 0x50, 0x70];
    9223           12 :         let mut leases = Vec::new();
    9224           36 :         leased_lsns.iter().for_each(|n| {
    9225           36 :             leases.push(
    9226           36 :                 timeline
    9227           36 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9228           36 :                     .expect("lease request should succeed"),
    9229           36 :             );
    9230           36 :         });
    9231           12 : 
    9232           12 :         let updated_lease_0 = timeline
    9233           12 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9234           12 :             .expect("lease renewal should succeed");
    9235           12 :         assert_eq!(
    9236           12 :             updated_lease_0.valid_until, leases[0].valid_until,
    9237           12 :             " Renewing with shorter lease should not change the lease."
    9238           12 :         );
    9239           12 : 
    9240           12 :         let updated_lease_1 = timeline
    9241           12 :             .renew_lsn_lease(
    9242           12 :                 Lsn(leased_lsns[1]),
    9243           12 :                 timeline.get_lsn_lease_length() * 2,
    9244           12 :                 &ctx,
    9245           12 :             )
    9246           12 :             .expect("lease renewal should succeed");
    9247           12 :         assert!(
    9248           12 :             updated_lease_1.valid_until > leases[1].valid_until,
    9249           12 :             "Renewing with a long lease should renew lease with later expiration time."
    9250           12 :         );
    9251           12 : 
    9252           12 :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9253           12 :         info!(
    9254           12 :             "applied_gc_cutoff_lsn: {}",
    9255            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9256           12 :         );
    9257           12 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9258           12 : 
    9259           12 :         let res = tenant
    9260           12 :             .gc_iteration(
    9261           12 :                 Some(TIMELINE_ID),
    9262           12 :                 0,
    9263           12 :                 Duration::ZERO,
    9264           12 :                 &CancellationToken::new(),
    9265           12 :                 &ctx,
    9266           12 :             )
    9267           12 :             .await
    9268           12 :             .unwrap();
    9269           12 : 
    9270           12 :         // Keeping everything <= Lsn(0x80) b/c leases:
    9271           12 :         // 0/10: initdb layer
    9272           12 :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9273           12 :         assert_eq!(res.layers_needed_by_leases, 7);
    9274           12 :         // Keeping 0/90 b/c it is the latest layer.
    9275           12 :         assert_eq!(res.layers_not_updated, 1);
    9276           12 :         // Removed 0/80.
    9277           12 :         assert_eq!(res.layers_removed, 1);
    9278           12 : 
    9279           12 :         // Make lease on a already GC-ed LSN.
    9280           12 :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9281           12 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9282           12 :         timeline
    9283           12 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9284           12 :             .expect_err("lease request on GC-ed LSN should fail");
    9285           12 : 
    9286           12 :         // Should still be able to renew a currently valid lease
    9287           12 :         // Assumption: original lease to is still valid for 0/50.
    9288           12 :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9289           12 :         timeline
    9290           12 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9291           12 :             .expect("lease renewal with validation should succeed");
    9292           12 : 
    9293           12 :         Ok(())
    9294           12 :     }
    9295              : 
    9296              :     #[cfg(feature = "testing")]
    9297              :     #[tokio::test]
    9298           12 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9299           12 :         test_simple_bottom_most_compaction_deltas_helper(
    9300           12 :             "test_simple_bottom_most_compaction_deltas_1",
    9301           12 :             false,
    9302           12 :         )
    9303           12 :         .await
    9304           12 :     }
    9305              : 
    9306              :     #[cfg(feature = "testing")]
    9307              :     #[tokio::test]
    9308           12 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9309           12 :         test_simple_bottom_most_compaction_deltas_helper(
    9310           12 :             "test_simple_bottom_most_compaction_deltas_2",
    9311           12 :             true,
    9312           12 :         )
    9313           12 :         .await
    9314           12 :     }
    9315              : 
    9316              :     #[cfg(feature = "testing")]
    9317           24 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9318           24 :         test_name: &'static str,
    9319           24 :         use_delta_bottom_layer: bool,
    9320           24 :     ) -> anyhow::Result<()> {
    9321           24 :         let harness = TenantHarness::create(test_name).await?;
    9322           24 :         let (tenant, ctx) = harness.load().await;
    9323              : 
    9324         1656 :         fn get_key(id: u32) -> Key {
    9325         1656 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9326         1656 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9327         1656 :             key.field6 = id;
    9328         1656 :             key
    9329         1656 :         }
    9330              : 
    9331              :         // We create
    9332              :         // - one bottom-most image layer,
    9333              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9334              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9335              :         // - a delta layer D3 above the horizon.
    9336              :         //
    9337              :         //                             | D3 |
    9338              :         //  | D1 |
    9339              :         // -|    |-- gc horizon -----------------
    9340              :         //  |    |                | D2 |
    9341              :         // --------- img layer ------------------
    9342              :         //
    9343              :         // What we should expact from this compaction is:
    9344              :         //                             | D3 |
    9345              :         //  | Part of D1 |
    9346              :         // --------- img layer with D1+D2 at GC horizon------------------
    9347              : 
    9348              :         // img layer at 0x10
    9349           24 :         let img_layer = (0..10)
    9350          240 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9351           24 :             .collect_vec();
    9352           24 :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9353           24 :         let delta4 = (0..10)
    9354          240 :             .map(|id| {
    9355          240 :                 (
    9356          240 :                     get_key(id),
    9357          240 :                     Lsn(0x08),
    9358          240 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9359          240 :                 )
    9360          240 :             })
    9361           24 :             .collect_vec();
    9362           24 : 
    9363           24 :         let delta1 = vec![
    9364           24 :             (
    9365           24 :                 get_key(1),
    9366           24 :                 Lsn(0x20),
    9367           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9368           24 :             ),
    9369           24 :             (
    9370           24 :                 get_key(2),
    9371           24 :                 Lsn(0x30),
    9372           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9373           24 :             ),
    9374           24 :             (
    9375           24 :                 get_key(3),
    9376           24 :                 Lsn(0x28),
    9377           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9378           24 :             ),
    9379           24 :             (
    9380           24 :                 get_key(3),
    9381           24 :                 Lsn(0x30),
    9382           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9383           24 :             ),
    9384           24 :             (
    9385           24 :                 get_key(3),
    9386           24 :                 Lsn(0x40),
    9387           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9388           24 :             ),
    9389           24 :         ];
    9390           24 :         let delta2 = vec![
    9391           24 :             (
    9392           24 :                 get_key(5),
    9393           24 :                 Lsn(0x20),
    9394           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9395           24 :             ),
    9396           24 :             (
    9397           24 :                 get_key(6),
    9398           24 :                 Lsn(0x20),
    9399           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9400           24 :             ),
    9401           24 :         ];
    9402           24 :         let delta3 = vec![
    9403           24 :             (
    9404           24 :                 get_key(8),
    9405           24 :                 Lsn(0x48),
    9406           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9407           24 :             ),
    9408           24 :             (
    9409           24 :                 get_key(9),
    9410           24 :                 Lsn(0x48),
    9411           24 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9412           24 :             ),
    9413           24 :         ];
    9414              : 
    9415           24 :         let tline = if use_delta_bottom_layer {
    9416           12 :             tenant
    9417           12 :                 .create_test_timeline_with_layers(
    9418           12 :                     TIMELINE_ID,
    9419           12 :                     Lsn(0x08),
    9420           12 :                     DEFAULT_PG_VERSION,
    9421           12 :                     &ctx,
    9422           12 :                     Vec::new(), // in-memory layers
    9423           12 :                     vec![
    9424           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9425           12 :                             Lsn(0x08)..Lsn(0x10),
    9426           12 :                             delta4,
    9427           12 :                         ),
    9428           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9429           12 :                             Lsn(0x20)..Lsn(0x48),
    9430           12 :                             delta1,
    9431           12 :                         ),
    9432           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9433           12 :                             Lsn(0x20)..Lsn(0x48),
    9434           12 :                             delta2,
    9435           12 :                         ),
    9436           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9437           12 :                             Lsn(0x48)..Lsn(0x50),
    9438           12 :                             delta3,
    9439           12 :                         ),
    9440           12 :                     ], // delta layers
    9441           12 :                     vec![],     // image layers
    9442           12 :                     Lsn(0x50),
    9443           12 :                 )
    9444           12 :                 .await?
    9445              :         } else {
    9446           12 :             tenant
    9447           12 :                 .create_test_timeline_with_layers(
    9448           12 :                     TIMELINE_ID,
    9449           12 :                     Lsn(0x10),
    9450           12 :                     DEFAULT_PG_VERSION,
    9451           12 :                     &ctx,
    9452           12 :                     Vec::new(), // in-memory layers
    9453           12 :                     vec![
    9454           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9455           12 :                             Lsn(0x10)..Lsn(0x48),
    9456           12 :                             delta1,
    9457           12 :                         ),
    9458           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9459           12 :                             Lsn(0x10)..Lsn(0x48),
    9460           12 :                             delta2,
    9461           12 :                         ),
    9462           12 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9463           12 :                             Lsn(0x48)..Lsn(0x50),
    9464           12 :                             delta3,
    9465           12 :                         ),
    9466           12 :                     ], // delta layers
    9467           12 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9468           12 :                     Lsn(0x50),
    9469           12 :                 )
    9470           12 :                 .await?
    9471              :         };
    9472              :         {
    9473           24 :             tline
    9474           24 :                 .applied_gc_cutoff_lsn
    9475           24 :                 .lock_for_write()
    9476           24 :                 .store_and_unlock(Lsn(0x30))
    9477           24 :                 .wait()
    9478           24 :                 .await;
    9479              :             // Update GC info
    9480           24 :             let mut guard = tline.gc_info.write().unwrap();
    9481           24 :             *guard = GcInfo {
    9482           24 :                 retain_lsns: vec![],
    9483           24 :                 cutoffs: GcCutoffs {
    9484           24 :                     time: Lsn(0x30),
    9485           24 :                     space: Lsn(0x30),
    9486           24 :                 },
    9487           24 :                 leases: Default::default(),
    9488           24 :                 within_ancestor_pitr: false,
    9489           24 :             };
    9490           24 :         }
    9491           24 : 
    9492           24 :         let expected_result = [
    9493           24 :             Bytes::from_static(b"value 0@0x10"),
    9494           24 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9495           24 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9496           24 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9497           24 :             Bytes::from_static(b"value 4@0x10"),
    9498           24 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9499           24 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9500           24 :             Bytes::from_static(b"value 7@0x10"),
    9501           24 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9502           24 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9503           24 :         ];
    9504           24 : 
    9505           24 :         let expected_result_at_gc_horizon = [
    9506           24 :             Bytes::from_static(b"value 0@0x10"),
    9507           24 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9508           24 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9509           24 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9510           24 :             Bytes::from_static(b"value 4@0x10"),
    9511           24 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9512           24 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9513           24 :             Bytes::from_static(b"value 7@0x10"),
    9514           24 :             Bytes::from_static(b"value 8@0x10"),
    9515           24 :             Bytes::from_static(b"value 9@0x10"),
    9516           24 :         ];
    9517              : 
    9518          264 :         for idx in 0..10 {
    9519          240 :             assert_eq!(
    9520          240 :                 tline
    9521          240 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9522          240 :                     .await
    9523          240 :                     .unwrap(),
    9524          240 :                 &expected_result[idx]
    9525              :             );
    9526          240 :             assert_eq!(
    9527          240 :                 tline
    9528          240 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9529          240 :                     .await
    9530          240 :                     .unwrap(),
    9531          240 :                 &expected_result_at_gc_horizon[idx]
    9532              :             );
    9533              :         }
    9534              : 
    9535           24 :         let cancel = CancellationToken::new();
    9536           24 :         tline
    9537           24 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9538           24 :             .await
    9539           24 :             .unwrap();
    9540              : 
    9541          264 :         for idx in 0..10 {
    9542          240 :             assert_eq!(
    9543          240 :                 tline
    9544          240 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9545          240 :                     .await
    9546          240 :                     .unwrap(),
    9547          240 :                 &expected_result[idx]
    9548              :             );
    9549          240 :             assert_eq!(
    9550          240 :                 tline
    9551          240 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9552          240 :                     .await
    9553          240 :                     .unwrap(),
    9554          240 :                 &expected_result_at_gc_horizon[idx]
    9555              :             );
    9556              :         }
    9557              : 
    9558              :         // increase GC horizon and compact again
    9559              :         {
    9560           24 :             tline
    9561           24 :                 .applied_gc_cutoff_lsn
    9562           24 :                 .lock_for_write()
    9563           24 :                 .store_and_unlock(Lsn(0x40))
    9564           24 :                 .wait()
    9565           24 :                 .await;
    9566              :             // Update GC info
    9567           24 :             let mut guard = tline.gc_info.write().unwrap();
    9568           24 :             guard.cutoffs.time = Lsn(0x40);
    9569           24 :             guard.cutoffs.space = Lsn(0x40);
    9570           24 :         }
    9571           24 :         tline
    9572           24 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9573           24 :             .await
    9574           24 :             .unwrap();
    9575           24 : 
    9576           24 :         Ok(())
    9577           24 :     }
    9578              : 
    9579              :     #[cfg(feature = "testing")]
    9580              :     #[tokio::test]
    9581           12 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9582           12 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9583           12 :         let (tenant, ctx) = harness.load().await;
    9584           12 :         let tline = tenant
    9585           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9586           12 :             .await?;
    9587           12 :         tline.force_advance_lsn(Lsn(0x70));
    9588           12 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9589           12 :         let history = vec![
    9590           12 :             (
    9591           12 :                 key,
    9592           12 :                 Lsn(0x10),
    9593           12 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9594           12 :             ),
    9595           12 :             (
    9596           12 :                 key,
    9597           12 :                 Lsn(0x20),
    9598           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9599           12 :             ),
    9600           12 :             (
    9601           12 :                 key,
    9602           12 :                 Lsn(0x30),
    9603           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9604           12 :             ),
    9605           12 :             (
    9606           12 :                 key,
    9607           12 :                 Lsn(0x40),
    9608           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9609           12 :             ),
    9610           12 :             (
    9611           12 :                 key,
    9612           12 :                 Lsn(0x50),
    9613           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9614           12 :             ),
    9615           12 :             (
    9616           12 :                 key,
    9617           12 :                 Lsn(0x60),
    9618           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9619           12 :             ),
    9620           12 :             (
    9621           12 :                 key,
    9622           12 :                 Lsn(0x70),
    9623           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9624           12 :             ),
    9625           12 :             (
    9626           12 :                 key,
    9627           12 :                 Lsn(0x80),
    9628           12 :                 Value::Image(Bytes::copy_from_slice(
    9629           12 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9630           12 :                 )),
    9631           12 :             ),
    9632           12 :             (
    9633           12 :                 key,
    9634           12 :                 Lsn(0x90),
    9635           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9636           12 :             ),
    9637           12 :         ];
    9638           12 :         let res = tline
    9639           12 :             .generate_key_retention(
    9640           12 :                 key,
    9641           12 :                 &history,
    9642           12 :                 Lsn(0x60),
    9643           12 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9644           12 :                 3,
    9645           12 :                 None,
    9646           12 :                 true,
    9647           12 :             )
    9648           12 :             .await
    9649           12 :             .unwrap();
    9650           12 :         let expected_res = KeyHistoryRetention {
    9651           12 :             below_horizon: vec![
    9652           12 :                 (
    9653           12 :                     Lsn(0x20),
    9654           12 :                     KeyLogAtLsn(vec![(
    9655           12 :                         Lsn(0x20),
    9656           12 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9657           12 :                     )]),
    9658           12 :                 ),
    9659           12 :                 (
    9660           12 :                     Lsn(0x40),
    9661           12 :                     KeyLogAtLsn(vec![
    9662           12 :                         (
    9663           12 :                             Lsn(0x30),
    9664           12 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9665           12 :                         ),
    9666           12 :                         (
    9667           12 :                             Lsn(0x40),
    9668           12 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9669           12 :                         ),
    9670           12 :                     ]),
    9671           12 :                 ),
    9672           12 :                 (
    9673           12 :                     Lsn(0x50),
    9674           12 :                     KeyLogAtLsn(vec![(
    9675           12 :                         Lsn(0x50),
    9676           12 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9677           12 :                     )]),
    9678           12 :                 ),
    9679           12 :                 (
    9680           12 :                     Lsn(0x60),
    9681           12 :                     KeyLogAtLsn(vec![(
    9682           12 :                         Lsn(0x60),
    9683           12 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9684           12 :                     )]),
    9685           12 :                 ),
    9686           12 :             ],
    9687           12 :             above_horizon: KeyLogAtLsn(vec![
    9688           12 :                 (
    9689           12 :                     Lsn(0x70),
    9690           12 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9691           12 :                 ),
    9692           12 :                 (
    9693           12 :                     Lsn(0x80),
    9694           12 :                     Value::Image(Bytes::copy_from_slice(
    9695           12 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9696           12 :                     )),
    9697           12 :                 ),
    9698           12 :                 (
    9699           12 :                     Lsn(0x90),
    9700           12 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9701           12 :                 ),
    9702           12 :             ]),
    9703           12 :         };
    9704           12 :         assert_eq!(res, expected_res);
    9705           12 : 
    9706           12 :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9707           12 :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9708           12 :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9709           12 :         // For example, we have
    9710           12 :         // ```plain
    9711           12 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9712           12 :         // ```
    9713           12 :         // Now the GC horizon moves up, and we have
    9714           12 :         // ```plain
    9715           12 :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9716           12 :         // ```
    9717           12 :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9718           12 :         // We will end up with
    9719           12 :         // ```plain
    9720           12 :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9721           12 :         // ```
    9722           12 :         // Now we run the GC-compaction, and this key does not have a full history.
    9723           12 :         // We should be able to handle this partial history and drop everything before the
    9724           12 :         // gc_horizon image.
    9725           12 : 
    9726           12 :         let history = vec![
    9727           12 :             (
    9728           12 :                 key,
    9729           12 :                 Lsn(0x20),
    9730           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9731           12 :             ),
    9732           12 :             (
    9733           12 :                 key,
    9734           12 :                 Lsn(0x30),
    9735           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9736           12 :             ),
    9737           12 :             (
    9738           12 :                 key,
    9739           12 :                 Lsn(0x40),
    9740           12 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9741           12 :             ),
    9742           12 :             (
    9743           12 :                 key,
    9744           12 :                 Lsn(0x50),
    9745           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9746           12 :             ),
    9747           12 :             (
    9748           12 :                 key,
    9749           12 :                 Lsn(0x60),
    9750           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9751           12 :             ),
    9752           12 :             (
    9753           12 :                 key,
    9754           12 :                 Lsn(0x70),
    9755           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9756           12 :             ),
    9757           12 :             (
    9758           12 :                 key,
    9759           12 :                 Lsn(0x80),
    9760           12 :                 Value::Image(Bytes::copy_from_slice(
    9761           12 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9762           12 :                 )),
    9763           12 :             ),
    9764           12 :             (
    9765           12 :                 key,
    9766           12 :                 Lsn(0x90),
    9767           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9768           12 :             ),
    9769           12 :         ];
    9770           12 :         let res = tline
    9771           12 :             .generate_key_retention(
    9772           12 :                 key,
    9773           12 :                 &history,
    9774           12 :                 Lsn(0x60),
    9775           12 :                 &[Lsn(0x40), Lsn(0x50)],
    9776           12 :                 3,
    9777           12 :                 None,
    9778           12 :                 true,
    9779           12 :             )
    9780           12 :             .await
    9781           12 :             .unwrap();
    9782           12 :         let expected_res = KeyHistoryRetention {
    9783           12 :             below_horizon: vec![
    9784           12 :                 (
    9785           12 :                     Lsn(0x40),
    9786           12 :                     KeyLogAtLsn(vec![(
    9787           12 :                         Lsn(0x40),
    9788           12 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
    9789           12 :                     )]),
    9790           12 :                 ),
    9791           12 :                 (
    9792           12 :                     Lsn(0x50),
    9793           12 :                     KeyLogAtLsn(vec![(
    9794           12 :                         Lsn(0x50),
    9795           12 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9796           12 :                     )]),
    9797           12 :                 ),
    9798           12 :                 (
    9799           12 :                     Lsn(0x60),
    9800           12 :                     KeyLogAtLsn(vec![(
    9801           12 :                         Lsn(0x60),
    9802           12 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9803           12 :                     )]),
    9804           12 :                 ),
    9805           12 :             ],
    9806           12 :             above_horizon: KeyLogAtLsn(vec![
    9807           12 :                 (
    9808           12 :                     Lsn(0x70),
    9809           12 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9810           12 :                 ),
    9811           12 :                 (
    9812           12 :                     Lsn(0x80),
    9813           12 :                     Value::Image(Bytes::copy_from_slice(
    9814           12 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9815           12 :                     )),
    9816           12 :                 ),
    9817           12 :                 (
    9818           12 :                     Lsn(0x90),
    9819           12 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9820           12 :                 ),
    9821           12 :             ]),
    9822           12 :         };
    9823           12 :         assert_eq!(res, expected_res);
    9824           12 : 
    9825           12 :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
    9826           12 :         // the ancestor image in the test case.
    9827           12 : 
    9828           12 :         let history = vec![
    9829           12 :             (
    9830           12 :                 key,
    9831           12 :                 Lsn(0x20),
    9832           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9833           12 :             ),
    9834           12 :             (
    9835           12 :                 key,
    9836           12 :                 Lsn(0x30),
    9837           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9838           12 :             ),
    9839           12 :             (
    9840           12 :                 key,
    9841           12 :                 Lsn(0x40),
    9842           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9843           12 :             ),
    9844           12 :             (
    9845           12 :                 key,
    9846           12 :                 Lsn(0x70),
    9847           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9848           12 :             ),
    9849           12 :         ];
    9850           12 :         let res = tline
    9851           12 :             .generate_key_retention(
    9852           12 :                 key,
    9853           12 :                 &history,
    9854           12 :                 Lsn(0x60),
    9855           12 :                 &[],
    9856           12 :                 3,
    9857           12 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9858           12 :                 true,
    9859           12 :             )
    9860           12 :             .await
    9861           12 :             .unwrap();
    9862           12 :         let expected_res = KeyHistoryRetention {
    9863           12 :             below_horizon: vec![(
    9864           12 :                 Lsn(0x60),
    9865           12 :                 KeyLogAtLsn(vec![(
    9866           12 :                     Lsn(0x60),
    9867           12 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
    9868           12 :                 )]),
    9869           12 :             )],
    9870           12 :             above_horizon: KeyLogAtLsn(vec![(
    9871           12 :                 Lsn(0x70),
    9872           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9873           12 :             )]),
    9874           12 :         };
    9875           12 :         assert_eq!(res, expected_res);
    9876           12 : 
    9877           12 :         let history = vec![
    9878           12 :             (
    9879           12 :                 key,
    9880           12 :                 Lsn(0x20),
    9881           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9882           12 :             ),
    9883           12 :             (
    9884           12 :                 key,
    9885           12 :                 Lsn(0x40),
    9886           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9887           12 :             ),
    9888           12 :             (
    9889           12 :                 key,
    9890           12 :                 Lsn(0x60),
    9891           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9892           12 :             ),
    9893           12 :             (
    9894           12 :                 key,
    9895           12 :                 Lsn(0x70),
    9896           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9897           12 :             ),
    9898           12 :         ];
    9899           12 :         let res = tline
    9900           12 :             .generate_key_retention(
    9901           12 :                 key,
    9902           12 :                 &history,
    9903           12 :                 Lsn(0x60),
    9904           12 :                 &[Lsn(0x30)],
    9905           12 :                 3,
    9906           12 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
    9907           12 :                 true,
    9908           12 :             )
    9909           12 :             .await
    9910           12 :             .unwrap();
    9911           12 :         let expected_res = KeyHistoryRetention {
    9912           12 :             below_horizon: vec![
    9913           12 :                 (
    9914           12 :                     Lsn(0x30),
    9915           12 :                     KeyLogAtLsn(vec![(
    9916           12 :                         Lsn(0x20),
    9917           12 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9918           12 :                     )]),
    9919           12 :                 ),
    9920           12 :                 (
    9921           12 :                     Lsn(0x60),
    9922           12 :                     KeyLogAtLsn(vec![(
    9923           12 :                         Lsn(0x60),
    9924           12 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
    9925           12 :                     )]),
    9926           12 :                 ),
    9927           12 :             ],
    9928           12 :             above_horizon: KeyLogAtLsn(vec![(
    9929           12 :                 Lsn(0x70),
    9930           12 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9931           12 :             )]),
    9932           12 :         };
    9933           12 :         assert_eq!(res, expected_res);
    9934           12 : 
    9935           12 :         Ok(())
    9936           12 :     }
    9937              : 
    9938              :     #[cfg(feature = "testing")]
    9939              :     #[tokio::test]
    9940           12 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
    9941           12 :         let harness =
    9942           12 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
    9943           12 :         let (tenant, ctx) = harness.load().await;
    9944           12 : 
    9945         3108 :         fn get_key(id: u32) -> Key {
    9946         3108 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9947         3108 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9948         3108 :             key.field6 = id;
    9949         3108 :             key
    9950         3108 :         }
    9951           12 : 
    9952           12 :         let img_layer = (0..10)
    9953          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9954           12 :             .collect_vec();
    9955           12 : 
    9956           12 :         let delta1 = vec![
    9957           12 :             (
    9958           12 :                 get_key(1),
    9959           12 :                 Lsn(0x20),
    9960           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9961           12 :             ),
    9962           12 :             (
    9963           12 :                 get_key(2),
    9964           12 :                 Lsn(0x30),
    9965           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9966           12 :             ),
    9967           12 :             (
    9968           12 :                 get_key(3),
    9969           12 :                 Lsn(0x28),
    9970           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9971           12 :             ),
    9972           12 :             (
    9973           12 :                 get_key(3),
    9974           12 :                 Lsn(0x30),
    9975           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9976           12 :             ),
    9977           12 :             (
    9978           12 :                 get_key(3),
    9979           12 :                 Lsn(0x40),
    9980           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9981           12 :             ),
    9982           12 :         ];
    9983           12 :         let delta2 = vec![
    9984           12 :             (
    9985           12 :                 get_key(5),
    9986           12 :                 Lsn(0x20),
    9987           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9988           12 :             ),
    9989           12 :             (
    9990           12 :                 get_key(6),
    9991           12 :                 Lsn(0x20),
    9992           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9993           12 :             ),
    9994           12 :         ];
    9995           12 :         let delta3 = vec![
    9996           12 :             (
    9997           12 :                 get_key(8),
    9998           12 :                 Lsn(0x48),
    9999           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10000           12 :             ),
   10001           12 :             (
   10002           12 :                 get_key(9),
   10003           12 :                 Lsn(0x48),
   10004           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10005           12 :             ),
   10006           12 :         ];
   10007           12 : 
   10008           12 :         let tline = tenant
   10009           12 :             .create_test_timeline_with_layers(
   10010           12 :                 TIMELINE_ID,
   10011           12 :                 Lsn(0x10),
   10012           12 :                 DEFAULT_PG_VERSION,
   10013           12 :                 &ctx,
   10014           12 :                 Vec::new(), // in-memory layers
   10015           12 :                 vec![
   10016           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
   10017           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
   10018           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10019           12 :                 ], // delta layers
   10020           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10021           12 :                 Lsn(0x50),
   10022           12 :             )
   10023           12 :             .await?;
   10024           12 :         {
   10025           12 :             tline
   10026           12 :                 .applied_gc_cutoff_lsn
   10027           12 :                 .lock_for_write()
   10028           12 :                 .store_and_unlock(Lsn(0x30))
   10029           12 :                 .wait()
   10030           12 :                 .await;
   10031           12 :             // Update GC info
   10032           12 :             let mut guard = tline.gc_info.write().unwrap();
   10033           12 :             *guard = GcInfo {
   10034           12 :                 retain_lsns: vec![
   10035           12 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10036           12 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10037           12 :                 ],
   10038           12 :                 cutoffs: GcCutoffs {
   10039           12 :                     time: Lsn(0x30),
   10040           12 :                     space: Lsn(0x30),
   10041           12 :                 },
   10042           12 :                 leases: Default::default(),
   10043           12 :                 within_ancestor_pitr: false,
   10044           12 :             };
   10045           12 :         }
   10046           12 : 
   10047           12 :         let expected_result = [
   10048           12 :             Bytes::from_static(b"value 0@0x10"),
   10049           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10050           12 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10051           12 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10052           12 :             Bytes::from_static(b"value 4@0x10"),
   10053           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10054           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10055           12 :             Bytes::from_static(b"value 7@0x10"),
   10056           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10057           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10058           12 :         ];
   10059           12 : 
   10060           12 :         let expected_result_at_gc_horizon = [
   10061           12 :             Bytes::from_static(b"value 0@0x10"),
   10062           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10063           12 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10064           12 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
   10065           12 :             Bytes::from_static(b"value 4@0x10"),
   10066           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10067           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10068           12 :             Bytes::from_static(b"value 7@0x10"),
   10069           12 :             Bytes::from_static(b"value 8@0x10"),
   10070           12 :             Bytes::from_static(b"value 9@0x10"),
   10071           12 :         ];
   10072           12 : 
   10073           12 :         let expected_result_at_lsn_20 = [
   10074           12 :             Bytes::from_static(b"value 0@0x10"),
   10075           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10076           12 :             Bytes::from_static(b"value 2@0x10"),
   10077           12 :             Bytes::from_static(b"value 3@0x10"),
   10078           12 :             Bytes::from_static(b"value 4@0x10"),
   10079           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10080           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10081           12 :             Bytes::from_static(b"value 7@0x10"),
   10082           12 :             Bytes::from_static(b"value 8@0x10"),
   10083           12 :             Bytes::from_static(b"value 9@0x10"),
   10084           12 :         ];
   10085           12 : 
   10086           12 :         let expected_result_at_lsn_10 = [
   10087           12 :             Bytes::from_static(b"value 0@0x10"),
   10088           12 :             Bytes::from_static(b"value 1@0x10"),
   10089           12 :             Bytes::from_static(b"value 2@0x10"),
   10090           12 :             Bytes::from_static(b"value 3@0x10"),
   10091           12 :             Bytes::from_static(b"value 4@0x10"),
   10092           12 :             Bytes::from_static(b"value 5@0x10"),
   10093           12 :             Bytes::from_static(b"value 6@0x10"),
   10094           12 :             Bytes::from_static(b"value 7@0x10"),
   10095           12 :             Bytes::from_static(b"value 8@0x10"),
   10096           12 :             Bytes::from_static(b"value 9@0x10"),
   10097           12 :         ];
   10098           12 : 
   10099           72 :         let verify_result = || async {
   10100           72 :             let gc_horizon = {
   10101           72 :                 let gc_info = tline.gc_info.read().unwrap();
   10102           72 :                 gc_info.cutoffs.time
   10103           12 :             };
   10104          792 :             for idx in 0..10 {
   10105          720 :                 assert_eq!(
   10106          720 :                     tline
   10107          720 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10108          720 :                         .await
   10109          720 :                         .unwrap(),
   10110          720 :                     &expected_result[idx]
   10111           12 :                 );
   10112          720 :                 assert_eq!(
   10113          720 :                     tline
   10114          720 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10115          720 :                         .await
   10116          720 :                         .unwrap(),
   10117          720 :                     &expected_result_at_gc_horizon[idx]
   10118           12 :                 );
   10119          720 :                 assert_eq!(
   10120          720 :                     tline
   10121          720 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10122          720 :                         .await
   10123          720 :                         .unwrap(),
   10124          720 :                     &expected_result_at_lsn_20[idx]
   10125           12 :                 );
   10126          720 :                 assert_eq!(
   10127          720 :                     tline
   10128          720 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10129          720 :                         .await
   10130          720 :                         .unwrap(),
   10131          720 :                     &expected_result_at_lsn_10[idx]
   10132           12 :                 );
   10133           12 :             }
   10134          144 :         };
   10135           12 : 
   10136           12 :         verify_result().await;
   10137           12 : 
   10138           12 :         let cancel = CancellationToken::new();
   10139           12 :         let mut dryrun_flags = EnumSet::new();
   10140           12 :         dryrun_flags.insert(CompactFlags::DryRun);
   10141           12 : 
   10142           12 :         tline
   10143           12 :             .compact_with_gc(
   10144           12 :                 &cancel,
   10145           12 :                 CompactOptions {
   10146           12 :                     flags: dryrun_flags,
   10147           12 :                     ..Default::default()
   10148           12 :                 },
   10149           12 :                 &ctx,
   10150           12 :             )
   10151           12 :             .await
   10152           12 :             .unwrap();
   10153           12 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
   10154           12 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10155           12 :         verify_result().await;
   10156           12 : 
   10157           12 :         tline
   10158           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10159           12 :             .await
   10160           12 :             .unwrap();
   10161           12 :         verify_result().await;
   10162           12 : 
   10163           12 :         // compact again
   10164           12 :         tline
   10165           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10166           12 :             .await
   10167           12 :             .unwrap();
   10168           12 :         verify_result().await;
   10169           12 : 
   10170           12 :         // increase GC horizon and compact again
   10171           12 :         {
   10172           12 :             tline
   10173           12 :                 .applied_gc_cutoff_lsn
   10174           12 :                 .lock_for_write()
   10175           12 :                 .store_and_unlock(Lsn(0x38))
   10176           12 :                 .wait()
   10177           12 :                 .await;
   10178           12 :             // Update GC info
   10179           12 :             let mut guard = tline.gc_info.write().unwrap();
   10180           12 :             guard.cutoffs.time = Lsn(0x38);
   10181           12 :             guard.cutoffs.space = Lsn(0x38);
   10182           12 :         }
   10183           12 :         tline
   10184           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10185           12 :             .await
   10186           12 :             .unwrap();
   10187           12 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10188           12 : 
   10189           12 :         // not increasing the GC horizon and compact again
   10190           12 :         tline
   10191           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10192           12 :             .await
   10193           12 :             .unwrap();
   10194           12 :         verify_result().await;
   10195           12 : 
   10196           12 :         Ok(())
   10197           12 :     }
   10198              : 
   10199              :     #[cfg(feature = "testing")]
   10200              :     #[tokio::test]
   10201           12 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10202           12 :     {
   10203           12 :         let harness =
   10204           12 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10205           12 :                 .await?;
   10206           12 :         let (tenant, ctx) = harness.load().await;
   10207           12 : 
   10208         2112 :         fn get_key(id: u32) -> Key {
   10209         2112 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10210         2112 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10211         2112 :             key.field6 = id;
   10212         2112 :             key
   10213         2112 :         }
   10214           12 : 
   10215           12 :         let img_layer = (0..10)
   10216          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10217           12 :             .collect_vec();
   10218           12 : 
   10219           12 :         let delta1 = vec![
   10220           12 :             (
   10221           12 :                 get_key(1),
   10222           12 :                 Lsn(0x20),
   10223           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10224           12 :             ),
   10225           12 :             (
   10226           12 :                 get_key(1),
   10227           12 :                 Lsn(0x28),
   10228           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10229           12 :             ),
   10230           12 :         ];
   10231           12 :         let delta2 = vec![
   10232           12 :             (
   10233           12 :                 get_key(1),
   10234           12 :                 Lsn(0x30),
   10235           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10236           12 :             ),
   10237           12 :             (
   10238           12 :                 get_key(1),
   10239           12 :                 Lsn(0x38),
   10240           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10241           12 :             ),
   10242           12 :         ];
   10243           12 :         let delta3 = vec![
   10244           12 :             (
   10245           12 :                 get_key(8),
   10246           12 :                 Lsn(0x48),
   10247           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10248           12 :             ),
   10249           12 :             (
   10250           12 :                 get_key(9),
   10251           12 :                 Lsn(0x48),
   10252           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10253           12 :             ),
   10254           12 :         ];
   10255           12 : 
   10256           12 :         let tline = tenant
   10257           12 :             .create_test_timeline_with_layers(
   10258           12 :                 TIMELINE_ID,
   10259           12 :                 Lsn(0x10),
   10260           12 :                 DEFAULT_PG_VERSION,
   10261           12 :                 &ctx,
   10262           12 :                 Vec::new(), // in-memory layers
   10263           12 :                 vec![
   10264           12 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10265           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10266           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10267           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10268           12 :                 ], // delta layers
   10269           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10270           12 :                 Lsn(0x50),
   10271           12 :             )
   10272           12 :             .await?;
   10273           12 :         {
   10274           12 :             tline
   10275           12 :                 .applied_gc_cutoff_lsn
   10276           12 :                 .lock_for_write()
   10277           12 :                 .store_and_unlock(Lsn(0x30))
   10278           12 :                 .wait()
   10279           12 :                 .await;
   10280           12 :             // Update GC info
   10281           12 :             let mut guard = tline.gc_info.write().unwrap();
   10282           12 :             *guard = GcInfo {
   10283           12 :                 retain_lsns: vec![
   10284           12 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10285           12 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10286           12 :                 ],
   10287           12 :                 cutoffs: GcCutoffs {
   10288           12 :                     time: Lsn(0x30),
   10289           12 :                     space: Lsn(0x30),
   10290           12 :                 },
   10291           12 :                 leases: Default::default(),
   10292           12 :                 within_ancestor_pitr: false,
   10293           12 :             };
   10294           12 :         }
   10295           12 : 
   10296           12 :         let expected_result = [
   10297           12 :             Bytes::from_static(b"value 0@0x10"),
   10298           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10299           12 :             Bytes::from_static(b"value 2@0x10"),
   10300           12 :             Bytes::from_static(b"value 3@0x10"),
   10301           12 :             Bytes::from_static(b"value 4@0x10"),
   10302           12 :             Bytes::from_static(b"value 5@0x10"),
   10303           12 :             Bytes::from_static(b"value 6@0x10"),
   10304           12 :             Bytes::from_static(b"value 7@0x10"),
   10305           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10306           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10307           12 :         ];
   10308           12 : 
   10309           12 :         let expected_result_at_gc_horizon = [
   10310           12 :             Bytes::from_static(b"value 0@0x10"),
   10311           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10312           12 :             Bytes::from_static(b"value 2@0x10"),
   10313           12 :             Bytes::from_static(b"value 3@0x10"),
   10314           12 :             Bytes::from_static(b"value 4@0x10"),
   10315           12 :             Bytes::from_static(b"value 5@0x10"),
   10316           12 :             Bytes::from_static(b"value 6@0x10"),
   10317           12 :             Bytes::from_static(b"value 7@0x10"),
   10318           12 :             Bytes::from_static(b"value 8@0x10"),
   10319           12 :             Bytes::from_static(b"value 9@0x10"),
   10320           12 :         ];
   10321           12 : 
   10322           12 :         let expected_result_at_lsn_20 = [
   10323           12 :             Bytes::from_static(b"value 0@0x10"),
   10324           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10325           12 :             Bytes::from_static(b"value 2@0x10"),
   10326           12 :             Bytes::from_static(b"value 3@0x10"),
   10327           12 :             Bytes::from_static(b"value 4@0x10"),
   10328           12 :             Bytes::from_static(b"value 5@0x10"),
   10329           12 :             Bytes::from_static(b"value 6@0x10"),
   10330           12 :             Bytes::from_static(b"value 7@0x10"),
   10331           12 :             Bytes::from_static(b"value 8@0x10"),
   10332           12 :             Bytes::from_static(b"value 9@0x10"),
   10333           12 :         ];
   10334           12 : 
   10335           12 :         let expected_result_at_lsn_10 = [
   10336           12 :             Bytes::from_static(b"value 0@0x10"),
   10337           12 :             Bytes::from_static(b"value 1@0x10"),
   10338           12 :             Bytes::from_static(b"value 2@0x10"),
   10339           12 :             Bytes::from_static(b"value 3@0x10"),
   10340           12 :             Bytes::from_static(b"value 4@0x10"),
   10341           12 :             Bytes::from_static(b"value 5@0x10"),
   10342           12 :             Bytes::from_static(b"value 6@0x10"),
   10343           12 :             Bytes::from_static(b"value 7@0x10"),
   10344           12 :             Bytes::from_static(b"value 8@0x10"),
   10345           12 :             Bytes::from_static(b"value 9@0x10"),
   10346           12 :         ];
   10347           12 : 
   10348           48 :         let verify_result = || async {
   10349           48 :             let gc_horizon = {
   10350           48 :                 let gc_info = tline.gc_info.read().unwrap();
   10351           48 :                 gc_info.cutoffs.time
   10352           12 :             };
   10353          528 :             for idx in 0..10 {
   10354          480 :                 assert_eq!(
   10355          480 :                     tline
   10356          480 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10357          480 :                         .await
   10358          480 :                         .unwrap(),
   10359          480 :                     &expected_result[idx]
   10360           12 :                 );
   10361          480 :                 assert_eq!(
   10362          480 :                     tline
   10363          480 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10364          480 :                         .await
   10365          480 :                         .unwrap(),
   10366          480 :                     &expected_result_at_gc_horizon[idx]
   10367           12 :                 );
   10368          480 :                 assert_eq!(
   10369          480 :                     tline
   10370          480 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10371          480 :                         .await
   10372          480 :                         .unwrap(),
   10373          480 :                     &expected_result_at_lsn_20[idx]
   10374           12 :                 );
   10375          480 :                 assert_eq!(
   10376          480 :                     tline
   10377          480 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10378          480 :                         .await
   10379          480 :                         .unwrap(),
   10380          480 :                     &expected_result_at_lsn_10[idx]
   10381           12 :                 );
   10382           12 :             }
   10383           96 :         };
   10384           12 : 
   10385           12 :         verify_result().await;
   10386           12 : 
   10387           12 :         let cancel = CancellationToken::new();
   10388           12 :         let mut dryrun_flags = EnumSet::new();
   10389           12 :         dryrun_flags.insert(CompactFlags::DryRun);
   10390           12 : 
   10391           12 :         tline
   10392           12 :             .compact_with_gc(
   10393           12 :                 &cancel,
   10394           12 :                 CompactOptions {
   10395           12 :                     flags: dryrun_flags,
   10396           12 :                     ..Default::default()
   10397           12 :                 },
   10398           12 :                 &ctx,
   10399           12 :             )
   10400           12 :             .await
   10401           12 :             .unwrap();
   10402           12 :         // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
   10403           12 :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10404           12 :         verify_result().await;
   10405           12 : 
   10406           12 :         tline
   10407           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10408           12 :             .await
   10409           12 :             .unwrap();
   10410           12 :         verify_result().await;
   10411           12 : 
   10412           12 :         // compact again
   10413           12 :         tline
   10414           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10415           12 :             .await
   10416           12 :             .unwrap();
   10417           12 :         verify_result().await;
   10418           12 : 
   10419           12 :         Ok(())
   10420           12 :     }
   10421              : 
   10422              :     #[cfg(feature = "testing")]
   10423              :     #[tokio::test]
   10424           12 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10425           12 :         use models::CompactLsnRange;
   10426           12 : 
   10427           12 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10428           12 :         let (tenant, ctx) = harness.load().await;
   10429           12 : 
   10430          996 :         fn get_key(id: u32) -> Key {
   10431          996 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10432          996 :             key.field6 = id;
   10433          996 :             key
   10434          996 :         }
   10435           12 : 
   10436           12 :         let img_layer = (0..10)
   10437          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10438           12 :             .collect_vec();
   10439           12 : 
   10440           12 :         let delta1 = vec![
   10441           12 :             (
   10442           12 :                 get_key(1),
   10443           12 :                 Lsn(0x20),
   10444           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10445           12 :             ),
   10446           12 :             (
   10447           12 :                 get_key(2),
   10448           12 :                 Lsn(0x30),
   10449           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10450           12 :             ),
   10451           12 :             (
   10452           12 :                 get_key(3),
   10453           12 :                 Lsn(0x28),
   10454           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10455           12 :             ),
   10456           12 :             (
   10457           12 :                 get_key(3),
   10458           12 :                 Lsn(0x30),
   10459           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10460           12 :             ),
   10461           12 :             (
   10462           12 :                 get_key(3),
   10463           12 :                 Lsn(0x40),
   10464           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10465           12 :             ),
   10466           12 :         ];
   10467           12 :         let delta2 = vec![
   10468           12 :             (
   10469           12 :                 get_key(5),
   10470           12 :                 Lsn(0x20),
   10471           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10472           12 :             ),
   10473           12 :             (
   10474           12 :                 get_key(6),
   10475           12 :                 Lsn(0x20),
   10476           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10477           12 :             ),
   10478           12 :         ];
   10479           12 :         let delta3 = vec![
   10480           12 :             (
   10481           12 :                 get_key(8),
   10482           12 :                 Lsn(0x48),
   10483           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10484           12 :             ),
   10485           12 :             (
   10486           12 :                 get_key(9),
   10487           12 :                 Lsn(0x48),
   10488           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10489           12 :             ),
   10490           12 :         ];
   10491           12 : 
   10492           12 :         let parent_tline = tenant
   10493           12 :             .create_test_timeline_with_layers(
   10494           12 :                 TIMELINE_ID,
   10495           12 :                 Lsn(0x10),
   10496           12 :                 DEFAULT_PG_VERSION,
   10497           12 :                 &ctx,
   10498           12 :                 vec![],                       // in-memory layers
   10499           12 :                 vec![],                       // delta layers
   10500           12 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10501           12 :                 Lsn(0x18),
   10502           12 :             )
   10503           12 :             .await?;
   10504           12 : 
   10505           12 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10506           12 : 
   10507           12 :         let branch_tline = tenant
   10508           12 :             .branch_timeline_test_with_layers(
   10509           12 :                 &parent_tline,
   10510           12 :                 NEW_TIMELINE_ID,
   10511           12 :                 Some(Lsn(0x18)),
   10512           12 :                 &ctx,
   10513           12 :                 vec![
   10514           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10515           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10516           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10517           12 :                 ], // delta layers
   10518           12 :                 vec![], // image layers
   10519           12 :                 Lsn(0x50),
   10520           12 :             )
   10521           12 :             .await?;
   10522           12 : 
   10523           12 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10524           12 : 
   10525           12 :         {
   10526           12 :             parent_tline
   10527           12 :                 .applied_gc_cutoff_lsn
   10528           12 :                 .lock_for_write()
   10529           12 :                 .store_and_unlock(Lsn(0x10))
   10530           12 :                 .wait()
   10531           12 :                 .await;
   10532           12 :             // Update GC info
   10533           12 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10534           12 :             *guard = GcInfo {
   10535           12 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10536           12 :                 cutoffs: GcCutoffs {
   10537           12 :                     time: Lsn(0x10),
   10538           12 :                     space: Lsn(0x10),
   10539           12 :                 },
   10540           12 :                 leases: Default::default(),
   10541           12 :                 within_ancestor_pitr: false,
   10542           12 :             };
   10543           12 :         }
   10544           12 : 
   10545           12 :         {
   10546           12 :             branch_tline
   10547           12 :                 .applied_gc_cutoff_lsn
   10548           12 :                 .lock_for_write()
   10549           12 :                 .store_and_unlock(Lsn(0x50))
   10550           12 :                 .wait()
   10551           12 :                 .await;
   10552           12 :             // Update GC info
   10553           12 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10554           12 :             *guard = GcInfo {
   10555           12 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10556           12 :                 cutoffs: GcCutoffs {
   10557           12 :                     time: Lsn(0x50),
   10558           12 :                     space: Lsn(0x50),
   10559           12 :                 },
   10560           12 :                 leases: Default::default(),
   10561           12 :                 within_ancestor_pitr: false,
   10562           12 :             };
   10563           12 :         }
   10564           12 : 
   10565           12 :         let expected_result_at_gc_horizon = [
   10566           12 :             Bytes::from_static(b"value 0@0x10"),
   10567           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10568           12 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10569           12 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10570           12 :             Bytes::from_static(b"value 4@0x10"),
   10571           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10572           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10573           12 :             Bytes::from_static(b"value 7@0x10"),
   10574           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10575           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10576           12 :         ];
   10577           12 : 
   10578           12 :         let expected_result_at_lsn_40 = [
   10579           12 :             Bytes::from_static(b"value 0@0x10"),
   10580           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10581           12 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10582           12 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10583           12 :             Bytes::from_static(b"value 4@0x10"),
   10584           12 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10585           12 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10586           12 :             Bytes::from_static(b"value 7@0x10"),
   10587           12 :             Bytes::from_static(b"value 8@0x10"),
   10588           12 :             Bytes::from_static(b"value 9@0x10"),
   10589           12 :         ];
   10590           12 : 
   10591           36 :         let verify_result = || async {
   10592          396 :             for idx in 0..10 {
   10593          360 :                 assert_eq!(
   10594          360 :                     branch_tline
   10595          360 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10596          360 :                         .await
   10597          360 :                         .unwrap(),
   10598          360 :                     &expected_result_at_gc_horizon[idx]
   10599           12 :                 );
   10600          360 :                 assert_eq!(
   10601          360 :                     branch_tline
   10602          360 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10603          360 :                         .await
   10604          360 :                         .unwrap(),
   10605          360 :                     &expected_result_at_lsn_40[idx]
   10606           12 :                 );
   10607           12 :             }
   10608           72 :         };
   10609           12 : 
   10610           12 :         verify_result().await;
   10611           12 : 
   10612           12 :         let cancel = CancellationToken::new();
   10613           12 :         branch_tline
   10614           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10615           12 :             .await
   10616           12 :             .unwrap();
   10617           12 : 
   10618           12 :         verify_result().await;
   10619           12 : 
   10620           12 :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10621           12 :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10622           12 :         branch_tline
   10623           12 :             .compact_with_gc(
   10624           12 :                 &cancel,
   10625           12 :                 CompactOptions {
   10626           12 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10627           12 :                     ..Default::default()
   10628           12 :                 },
   10629           12 :                 &ctx,
   10630           12 :             )
   10631           12 :             .await
   10632           12 :             .unwrap();
   10633           12 : 
   10634           12 :         verify_result().await;
   10635           12 : 
   10636           12 :         Ok(())
   10637           12 :     }
   10638              : 
   10639              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10640              :     // Create an image arrangement where we have to read at different LSN ranges
   10641              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10642              :     // a delta layer. Like so:
   10643              :     //
   10644              :     //     A      B
   10645              :     // +----------------+ -> delta_layer
   10646              :     // |                |                           ^ lsn
   10647              :     // |       =========|-> nested_image_layer      |
   10648              :     // |       C        |                           |
   10649              :     // +----------------+                           |
   10650              :     // ======== -> baseline_image_layer             +-------> key
   10651              :     //
   10652              :     //
   10653              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10654              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10655              :     #[cfg(feature = "testing")]
   10656              :     #[tokio::test]
   10657           12 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10658           12 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10659           12 :         let (tenant, ctx) = harness.load().await;
   10660           12 : 
   10661           12 :         let will_init_keys = [2, 6];
   10662          264 :         fn get_key(id: u32) -> Key {
   10663          264 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10664          264 :             key.field6 = id;
   10665          264 :             key
   10666          264 :         }
   10667           12 : 
   10668           12 :         let mut expected_key_values = HashMap::new();
   10669           12 : 
   10670           12 :         let baseline_image_layer_lsn = Lsn(0x10);
   10671           12 :         let mut baseline_img_layer = Vec::new();
   10672           72 :         for i in 0..5 {
   10673           60 :             let key = get_key(i);
   10674           60 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10675           60 : 
   10676           60 :             let removed = expected_key_values.insert(key, value.clone());
   10677           60 :             assert!(removed.is_none());
   10678           12 : 
   10679           60 :             baseline_img_layer.push((key, Bytes::from(value)));
   10680           12 :         }
   10681           12 : 
   10682           12 :         let nested_image_layer_lsn = Lsn(0x50);
   10683           12 :         let mut nested_img_layer = Vec::new();
   10684           72 :         for i in 5..10 {
   10685           60 :             let key = get_key(i);
   10686           60 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10687           60 : 
   10688           60 :             let removed = expected_key_values.insert(key, value.clone());
   10689           60 :             assert!(removed.is_none());
   10690           12 : 
   10691           60 :             nested_img_layer.push((key, Bytes::from(value)));
   10692           12 :         }
   10693           12 : 
   10694           12 :         let mut delta_layer_spec = Vec::default();
   10695           12 :         let delta_layer_start_lsn = Lsn(0x20);
   10696           12 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10697           12 : 
   10698          132 :         for i in 0..10 {
   10699          120 :             let key = get_key(i);
   10700          120 :             let key_in_nested = nested_img_layer
   10701          120 :                 .iter()
   10702          480 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10703          120 :             let lsn = {
   10704          120 :                 if key_in_nested {
   10705           60 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10706           12 :                 } else {
   10707           60 :                     delta_layer_start_lsn
   10708           12 :                 }
   10709           12 :             };
   10710           12 : 
   10711          120 :             let will_init = will_init_keys.contains(&i);
   10712          120 :             if will_init {
   10713           24 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10714           24 : 
   10715           24 :                 expected_key_values.insert(key, "".to_string());
   10716           96 :             } else {
   10717           96 :                 let delta = format!("@{lsn}");
   10718           96 :                 delta_layer_spec.push((
   10719           96 :                     key,
   10720           96 :                     lsn,
   10721           96 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10722           96 :                 ));
   10723           96 : 
   10724           96 :                 expected_key_values
   10725           96 :                     .get_mut(&key)
   10726           96 :                     .expect("An image exists for each key")
   10727           96 :                     .push_str(delta.as_str());
   10728           96 :             }
   10729          120 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10730           12 :         }
   10731           12 : 
   10732           12 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   10733           12 : 
   10734           12 :         assert!(
   10735           12 :             nested_image_layer_lsn > delta_layer_start_lsn
   10736           12 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   10737           12 :         );
   10738           12 : 
   10739           12 :         let tline = tenant
   10740           12 :             .create_test_timeline_with_layers(
   10741           12 :                 TIMELINE_ID,
   10742           12 :                 baseline_image_layer_lsn,
   10743           12 :                 DEFAULT_PG_VERSION,
   10744           12 :                 &ctx,
   10745           12 :                 vec![], // in-memory layers
   10746           12 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   10747           12 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   10748           12 :                     delta_layer_spec,
   10749           12 :                 )], // delta layers
   10750           12 :                 vec![
   10751           12 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10752           12 :                     (nested_image_layer_lsn, nested_img_layer),
   10753           12 :                 ], // image layers
   10754           12 :                 delta_layer_end_lsn,
   10755           12 :             )
   10756           12 :             .await?;
   10757           12 : 
   10758           12 :         let query = VersionedKeySpaceQuery::uniform(
   10759           12 :             KeySpace::single(get_key(0)..get_key(10)),
   10760           12 :             delta_layer_end_lsn,
   10761           12 :         );
   10762           12 : 
   10763           12 :         let results = tline
   10764           12 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   10765           12 :             .await
   10766           12 :             .expect("No vectored errors");
   10767          132 :         for (key, res) in results {
   10768          120 :             let value = res.expect("No key errors");
   10769          120 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10770          120 :             assert_eq!(value, Bytes::from(expected_value));
   10771           12 :         }
   10772           12 : 
   10773           12 :         Ok(())
   10774           12 :     }
   10775              : 
   10776              :     #[cfg(feature = "testing")]
   10777              :     #[tokio::test]
   10778           12 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   10779           12 :         let harness =
   10780           12 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   10781           12 :         let (tenant, ctx) = harness.load().await;
   10782           12 : 
   10783           12 :         let will_init_keys = [2, 6];
   10784          384 :         fn get_key(id: u32) -> Key {
   10785          384 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10786          384 :             key.field6 = id;
   10787          384 :             key
   10788          384 :         }
   10789           12 : 
   10790           12 :         let mut expected_key_values = HashMap::new();
   10791           12 : 
   10792           12 :         let baseline_image_layer_lsn = Lsn(0x10);
   10793           12 :         let mut baseline_img_layer = Vec::new();
   10794           72 :         for i in 0..5 {
   10795           60 :             let key = get_key(i);
   10796           60 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10797           60 : 
   10798           60 :             let removed = expected_key_values.insert(key, value.clone());
   10799           60 :             assert!(removed.is_none());
   10800           12 : 
   10801           60 :             baseline_img_layer.push((key, Bytes::from(value)));
   10802           12 :         }
   10803           12 : 
   10804           12 :         let nested_image_layer_lsn = Lsn(0x50);
   10805           12 :         let mut nested_img_layer = Vec::new();
   10806           72 :         for i in 5..10 {
   10807           60 :             let key = get_key(i);
   10808           60 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10809           60 : 
   10810           60 :             let removed = expected_key_values.insert(key, value.clone());
   10811           60 :             assert!(removed.is_none());
   10812           12 : 
   10813           60 :             nested_img_layer.push((key, Bytes::from(value)));
   10814           12 :         }
   10815           12 : 
   10816           12 :         let frozen_layer = {
   10817           12 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   10818           12 :             let mut data = Vec::new();
   10819          132 :             for i in 0..10 {
   10820          120 :                 let key = get_key(i);
   10821          120 :                 let key_in_nested = nested_img_layer
   10822          120 :                     .iter()
   10823          480 :                     .any(|(key_with_img, _)| *key_with_img == key);
   10824          120 :                 let lsn = {
   10825          120 :                     if key_in_nested {
   10826           60 :                         Lsn(nested_image_layer_lsn.0 + 5)
   10827           12 :                     } else {
   10828           60 :                         lsn_range.start
   10829           12 :                     }
   10830           12 :                 };
   10831           12 : 
   10832          120 :                 let will_init = will_init_keys.contains(&i);
   10833          120 :                 if will_init {
   10834           24 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10835           24 : 
   10836           24 :                     expected_key_values.insert(key, "".to_string());
   10837           96 :                 } else {
   10838           96 :                     let delta = format!("@{lsn}");
   10839           96 :                     data.push((
   10840           96 :                         key,
   10841           96 :                         lsn,
   10842           96 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10843           96 :                     ));
   10844           96 : 
   10845           96 :                     expected_key_values
   10846           96 :                         .get_mut(&key)
   10847           96 :                         .expect("An image exists for each key")
   10848           96 :                         .push_str(delta.as_str());
   10849           96 :                 }
   10850           12 :             }
   10851           12 : 
   10852           12 :             InMemoryLayerTestDesc {
   10853           12 :                 lsn_range,
   10854           12 :                 is_open: false,
   10855           12 :                 data,
   10856           12 :             }
   10857           12 :         };
   10858           12 : 
   10859           12 :         let (open_layer, last_record_lsn) = {
   10860           12 :             let start_lsn = Lsn(0x70);
   10861           12 :             let mut data = Vec::new();
   10862           12 :             let mut end_lsn = Lsn(0);
   10863          132 :             for i in 0..10 {
   10864          120 :                 let key = get_key(i);
   10865          120 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   10866          120 :                 let delta = format!("@{lsn}");
   10867          120 :                 data.push((
   10868          120 :                     key,
   10869          120 :                     lsn,
   10870          120 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10871          120 :                 ));
   10872          120 : 
   10873          120 :                 expected_key_values
   10874          120 :                     .get_mut(&key)
   10875          120 :                     .expect("An image exists for each key")
   10876          120 :                     .push_str(delta.as_str());
   10877          120 : 
   10878          120 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   10879          120 :             }
   10880           12 : 
   10881           12 :             (
   10882           12 :                 InMemoryLayerTestDesc {
   10883           12 :                     lsn_range: start_lsn..Lsn::MAX,
   10884           12 :                     is_open: true,
   10885           12 :                     data,
   10886           12 :                 },
   10887           12 :                 end_lsn,
   10888           12 :             )
   10889           12 :         };
   10890           12 : 
   10891           12 :         assert!(
   10892           12 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   10893           12 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   10894           12 :         );
   10895           12 : 
   10896           12 :         let tline = tenant
   10897           12 :             .create_test_timeline_with_layers(
   10898           12 :                 TIMELINE_ID,
   10899           12 :                 baseline_image_layer_lsn,
   10900           12 :                 DEFAULT_PG_VERSION,
   10901           12 :                 &ctx,
   10902           12 :                 vec![open_layer, frozen_layer], // in-memory layers
   10903           12 :                 Vec::new(),                     // delta layers
   10904           12 :                 vec![
   10905           12 :                     (baseline_image_layer_lsn, baseline_img_layer),
   10906           12 :                     (nested_image_layer_lsn, nested_img_layer),
   10907           12 :                 ], // image layers
   10908           12 :                 last_record_lsn,
   10909           12 :             )
   10910           12 :             .await?;
   10911           12 : 
   10912           12 :         let query = VersionedKeySpaceQuery::uniform(
   10913           12 :             KeySpace::single(get_key(0)..get_key(10)),
   10914           12 :             last_record_lsn,
   10915           12 :         );
   10916           12 : 
   10917           12 :         let results = tline
   10918           12 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   10919           12 :             .await
   10920           12 :             .expect("No vectored errors");
   10921          132 :         for (key, res) in results {
   10922          120 :             let value = res.expect("No key errors");
   10923          120 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   10924          120 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   10925           12 : 
   10926          120 :             tracing::info!("key={key} value={expected_value}");
   10927           12 :         }
   10928           12 : 
   10929           12 :         Ok(())
   10930           12 :     }
   10931              : 
   10932              :     // A randomized read path test. Generates a layer map according to a deterministic
   10933              :     // specification. Fills the (key, LSN) space in random manner and then performs
   10934              :     // random scattered queries validating the results against in-memory storage.
   10935              :     //
   10936              :     // See this internal Notion page for a diagram of the layer map:
   10937              :     // https://www.notion.so/neondatabase/Read-Path-Unit-Testing-Fuzzing-1d1f189e0047806c8e5cd37781b0a350?pvs=4
   10938              :     //
   10939              :     // A fuzzing mode is also supported. In this mode, the test will use a random
   10940              :     // seed instead of a hardcoded one. Use it in conjunction with `cargo stress`
   10941              :     // to run multiple instances in parallel:
   10942              :     //
   10943              :     // $ RUST_BACKTRACE=1 RUST_LOG=INFO \
   10944              :     //   cargo stress --package=pageserver --features=testing,fuzz-read-path --release -- test_read_path
   10945              :     #[cfg(feature = "testing")]
   10946              :     #[tokio::test]
   10947           12 :     async fn test_read_path() -> anyhow::Result<()> {
   10948           12 :         use rand::seq::SliceRandom;
   10949           12 : 
   10950           12 :         let seed = if cfg!(feature = "fuzz-read-path") {
   10951           12 :             let seed: u64 = thread_rng().r#gen();
   10952            0 :             seed
   10953           12 :         } else {
   10954           12 :             // Use a hard-coded seed when not in fuzzing mode.
   10955           12 :             // Note that with the current approach results are not reproducible
   10956           12 :             // accross platforms and Rust releases.
   10957           12 :             const SEED: u64 = 0;
   10958           12 :             SEED
   10959           12 :         };
   10960           12 : 
   10961           12 :         let mut random = StdRng::seed_from_u64(seed);
   10962           12 : 
   10963           12 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   10964           12 :             const QUERIES: u64 = 5000;
   10965           12 :             let will_init_chance: u8 = random.gen_range(0..=10);
   10966            0 :             let gap_chance: u8 = random.gen_range(0..=50);
   10967            0 : 
   10968            0 :             (QUERIES, will_init_chance, gap_chance)
   10969           12 :         } else {
   10970           12 :             const QUERIES: u64 = 1000;
   10971           12 :             const WILL_INIT_CHANCE: u8 = 1;
   10972           12 :             const GAP_CHANCE: u8 = 5;
   10973           12 : 
   10974           12 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   10975           12 :         };
   10976           12 : 
   10977           12 :         let harness = TenantHarness::create("test_read_path").await?;
   10978           12 :         let (tenant, ctx) = harness.load().await;
   10979           12 : 
   10980           12 :         tracing::info!("Using random seed: {seed}");
   10981           12 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   10982           12 : 
   10983           12 :         // Define the layer map shape. Note that this part is not randomized.
   10984           12 : 
   10985           12 :         const KEY_DIMENSION_SIZE: u32 = 99;
   10986           12 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10987           12 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   10988           12 :         let total_key_range = start_key..end_key;
   10989           12 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   10990           12 :         let total_start_lsn = Lsn(104);
   10991           12 :         let last_record_lsn = Lsn(504);
   10992           12 : 
   10993           12 :         assert!(total_key_range_size % 3 == 0);
   10994           12 : 
   10995           12 :         let in_memory_layers_shape = vec![
   10996           12 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   10997           12 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   10998           12 :         ];
   10999           12 : 
   11000           12 :         let delta_layers_shape = vec![
   11001           12 :             (
   11002           12 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   11003           12 :                 Lsn(200)..Lsn(304),
   11004           12 :             ),
   11005           12 :             (
   11006           12 :                 (start_key.add((total_key_range_size / 3) as u32))
   11007           12 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   11008           12 :                 Lsn(200)..Lsn(304),
   11009           12 :             ),
   11010           12 :             (
   11011           12 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   11012           12 :                     ..(start_key.add(total_key_range_size as u32)),
   11013           12 :                 Lsn(200)..Lsn(304),
   11014           12 :             ),
   11015           12 :         ];
   11016           12 : 
   11017           12 :         let image_layers_shape = vec![
   11018           12 :             (
   11019           12 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   11020           12 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   11021           12 :                 Lsn(456),
   11022           12 :             ),
   11023           12 :             (
   11024           12 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   11025           12 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   11026           12 :                 Lsn(256),
   11027           12 :             ),
   11028           12 :             (total_key_range.clone(), total_start_lsn),
   11029           12 :         ];
   11030           12 : 
   11031           12 :         let specification = TestTimelineSpecification {
   11032           12 :             start_lsn: total_start_lsn,
   11033           12 :             last_record_lsn,
   11034           12 :             in_memory_layers_shape,
   11035           12 :             delta_layers_shape,
   11036           12 :             image_layers_shape,
   11037           12 :             gap_chance,
   11038           12 :             will_init_chance,
   11039           12 :         };
   11040           12 : 
   11041           12 :         // Create and randomly fill in the layers according to the specification
   11042           12 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   11043           12 :             &tenant,
   11044           12 :             TIMELINE_ID,
   11045           12 :             DEFAULT_PG_VERSION,
   11046           12 :             specification,
   11047           12 :             &mut random,
   11048           12 :             &ctx,
   11049           12 :         )
   11050           12 :         .await?;
   11051           12 : 
   11052           12 :         // Now generate queries based on the interesting lsns that we've collected.
   11053           12 :         //
   11054           12 :         // While there's still room in the query, pick and interesting LSN and a random
   11055           12 :         // key. Then roll the dice to see if the next key should also be included in
   11056           12 :         // the query. When the roll fails, break the "batch" and pick another point in the
   11057           12 :         // (key, LSN) space.
   11058           12 : 
   11059           12 :         const PICK_NEXT_CHANCE: u8 = 50;
   11060           12 :         for _ in 0..queries {
   11061        12000 :             let query = {
   11062        12000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   11063        12000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   11064           12 : 
   11065       270432 :                 while used_keys.len() < Timeline::MAX_GET_VECTORED_KEYS as usize {
   11066       258432 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11067       258432 :                     let mut selected_key = start_key.add(random.gen_range(0..KEY_DIMENSION_SIZE));
   11068           12 : 
   11069       451368 :                     while used_keys.len() < Timeline::MAX_GET_VECTORED_KEYS as usize {
   11070       445116 :                         if used_keys.contains(&selected_key)
   11071       385848 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11072           12 :                         {
   11073        61116 :                             break;
   11074       384000 :                         }
   11075       384000 : 
   11076       384000 :                         keyspaces_at_lsn
   11077       384000 :                             .entry(*selected_lsn)
   11078       384000 :                             .or_default()
   11079       384000 :                             .add_key(selected_key);
   11080       384000 :                         used_keys.insert(selected_key);
   11081       384000 : 
   11082       384000 :                         let pick_next = random.gen_range(0..=100) <= PICK_NEXT_CHANCE;
   11083       384000 :                         if pick_next {
   11084       192936 :                             selected_key = selected_key.next();
   11085       192936 :                         } else {
   11086       191064 :                             break;
   11087           12 :                         }
   11088           12 :                     }
   11089           12 :                 }
   11090           12 : 
   11091        12000 :                 VersionedKeySpaceQuery::scattered(
   11092        12000 :                     keyspaces_at_lsn
   11093        12000 :                         .into_iter()
   11094       143004 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11095        12000 :                         .collect(),
   11096        12000 :                 )
   11097           12 :             };
   11098           12 : 
   11099           12 :             // Run the query and validate the results
   11100           12 : 
   11101        12000 :             let results = tline
   11102        12000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11103        12000 :                 .await;
   11104           12 : 
   11105        12000 :             let blobs = match results {
   11106        12000 :                 Ok(ok) => ok,
   11107           12 :                 Err(err) => {
   11108            0 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11109           12 :                 }
   11110           12 :             };
   11111           12 : 
   11112       384000 :             for (key, key_res) in blobs.into_iter() {
   11113       384000 :                 match key_res {
   11114       384000 :                     Ok(blob) => {
   11115       384000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11116       384000 :                         let expected = storage.get(key, requested_at_lsn);
   11117       384000 : 
   11118       384000 :                         if blob != expected {
   11119           12 :                             tracing::error!(
   11120           12 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11121           12 :                             );
   11122       384000 :                         }
   11123           12 : 
   11124       384000 :                         assert_eq!(blob, expected);
   11125           12 :                     }
   11126           12 :                     Err(err) => {
   11127            0 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11128            0 : 
   11129            0 :                         panic!(
   11130            0 :                             "seed={seed} Error returned for {key}@{requested_at_lsn} from query {query}: {err}"
   11131            0 :                         );
   11132           12 :                     }
   11133           12 :                 }
   11134           12 :             }
   11135           12 :         }
   11136           12 : 
   11137           12 :         Ok(())
   11138           12 :     }
   11139              : 
   11140         1284 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11141         1284 :         (
   11142         1284 :             k1.is_delta,
   11143         1284 :             k1.key_range.start,
   11144         1284 :             k1.key_range.end,
   11145         1284 :             k1.lsn_range.start,
   11146         1284 :             k1.lsn_range.end,
   11147         1284 :         )
   11148         1284 :             .cmp(&(
   11149         1284 :                 k2.is_delta,
   11150         1284 :                 k2.key_range.start,
   11151         1284 :                 k2.key_range.end,
   11152         1284 :                 k2.lsn_range.start,
   11153         1284 :                 k2.lsn_range.end,
   11154         1284 :             ))
   11155         1284 :     }
   11156              : 
   11157          144 :     async fn inspect_and_sort(
   11158          144 :         tline: &Arc<Timeline>,
   11159          144 :         filter: Option<std::ops::Range<Key>>,
   11160          144 :     ) -> Vec<PersistentLayerKey> {
   11161          144 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11162          144 :         if let Some(filter) = filter {
   11163          648 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11164          132 :         }
   11165          144 :         all_layers.sort_by(sort_layer_key);
   11166          144 :         all_layers
   11167          144 :     }
   11168              : 
   11169              :     #[cfg(feature = "testing")]
   11170          132 :     fn check_layer_map_key_eq(
   11171          132 :         mut left: Vec<PersistentLayerKey>,
   11172          132 :         mut right: Vec<PersistentLayerKey>,
   11173          132 :     ) {
   11174          132 :         left.sort_by(sort_layer_key);
   11175          132 :         right.sort_by(sort_layer_key);
   11176          132 :         if left != right {
   11177            0 :             eprintln!("---LEFT---");
   11178            0 :             for left in left.iter() {
   11179            0 :                 eprintln!("{}", left);
   11180            0 :             }
   11181            0 :             eprintln!("---RIGHT---");
   11182            0 :             for right in right.iter() {
   11183            0 :                 eprintln!("{}", right);
   11184            0 :             }
   11185            0 :             assert_eq!(left, right);
   11186          132 :         }
   11187          132 :     }
   11188              : 
   11189              :     #[cfg(feature = "testing")]
   11190              :     #[tokio::test]
   11191           12 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11192           12 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11193           12 :         let (tenant, ctx) = harness.load().await;
   11194           12 : 
   11195         1092 :         fn get_key(id: u32) -> Key {
   11196         1092 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11197         1092 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11198         1092 :             key.field6 = id;
   11199         1092 :             key
   11200         1092 :         }
   11201           12 : 
   11202           12 :         // img layer at 0x10
   11203           12 :         let img_layer = (0..10)
   11204          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11205           12 :             .collect_vec();
   11206           12 : 
   11207           12 :         let delta1 = vec![
   11208           12 :             (
   11209           12 :                 get_key(1),
   11210           12 :                 Lsn(0x20),
   11211           12 :                 Value::Image(Bytes::from("value 1@0x20")),
   11212           12 :             ),
   11213           12 :             (
   11214           12 :                 get_key(2),
   11215           12 :                 Lsn(0x30),
   11216           12 :                 Value::Image(Bytes::from("value 2@0x30")),
   11217           12 :             ),
   11218           12 :             (
   11219           12 :                 get_key(3),
   11220           12 :                 Lsn(0x40),
   11221           12 :                 Value::Image(Bytes::from("value 3@0x40")),
   11222           12 :             ),
   11223           12 :         ];
   11224           12 :         let delta2 = vec![
   11225           12 :             (
   11226           12 :                 get_key(5),
   11227           12 :                 Lsn(0x20),
   11228           12 :                 Value::Image(Bytes::from("value 5@0x20")),
   11229           12 :             ),
   11230           12 :             (
   11231           12 :                 get_key(6),
   11232           12 :                 Lsn(0x20),
   11233           12 :                 Value::Image(Bytes::from("value 6@0x20")),
   11234           12 :             ),
   11235           12 :         ];
   11236           12 :         let delta3 = vec![
   11237           12 :             (
   11238           12 :                 get_key(8),
   11239           12 :                 Lsn(0x48),
   11240           12 :                 Value::Image(Bytes::from("value 8@0x48")),
   11241           12 :             ),
   11242           12 :             (
   11243           12 :                 get_key(9),
   11244           12 :                 Lsn(0x48),
   11245           12 :                 Value::Image(Bytes::from("value 9@0x48")),
   11246           12 :             ),
   11247           12 :         ];
   11248           12 : 
   11249           12 :         let tline = tenant
   11250           12 :             .create_test_timeline_with_layers(
   11251           12 :                 TIMELINE_ID,
   11252           12 :                 Lsn(0x10),
   11253           12 :                 DEFAULT_PG_VERSION,
   11254           12 :                 &ctx,
   11255           12 :                 vec![], // in-memory layers
   11256           12 :                 vec![
   11257           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11258           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11259           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11260           12 :                 ], // delta layers
   11261           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11262           12 :                 Lsn(0x50),
   11263           12 :             )
   11264           12 :             .await?;
   11265           12 : 
   11266           12 :         {
   11267           12 :             tline
   11268           12 :                 .applied_gc_cutoff_lsn
   11269           12 :                 .lock_for_write()
   11270           12 :                 .store_and_unlock(Lsn(0x30))
   11271           12 :                 .wait()
   11272           12 :                 .await;
   11273           12 :             // Update GC info
   11274           12 :             let mut guard = tline.gc_info.write().unwrap();
   11275           12 :             *guard = GcInfo {
   11276           12 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11277           12 :                 cutoffs: GcCutoffs {
   11278           12 :                     time: Lsn(0x30),
   11279           12 :                     space: Lsn(0x30),
   11280           12 :                 },
   11281           12 :                 leases: Default::default(),
   11282           12 :                 within_ancestor_pitr: false,
   11283           12 :             };
   11284           12 :         }
   11285           12 : 
   11286           12 :         let cancel = CancellationToken::new();
   11287           12 : 
   11288           12 :         // Do a partial compaction on key range 0..2
   11289           12 :         tline
   11290           12 :             .compact_with_gc(
   11291           12 :                 &cancel,
   11292           12 :                 CompactOptions {
   11293           12 :                     flags: EnumSet::new(),
   11294           12 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11295           12 :                     ..Default::default()
   11296           12 :                 },
   11297           12 :                 &ctx,
   11298           12 :             )
   11299           12 :             .await
   11300           12 :             .unwrap();
   11301           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11302           12 :         check_layer_map_key_eq(
   11303           12 :             all_layers,
   11304           12 :             vec![
   11305           12 :                 // newly-generated image layer for the partial compaction range 0-2
   11306           12 :                 PersistentLayerKey {
   11307           12 :                     key_range: get_key(0)..get_key(2),
   11308           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11309           12 :                     is_delta: false,
   11310           12 :                 },
   11311           12 :                 PersistentLayerKey {
   11312           12 :                     key_range: get_key(0)..get_key(10),
   11313           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11314           12 :                     is_delta: false,
   11315           12 :                 },
   11316           12 :                 // delta1 is split and the second part is rewritten
   11317           12 :                 PersistentLayerKey {
   11318           12 :                     key_range: get_key(2)..get_key(4),
   11319           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11320           12 :                     is_delta: true,
   11321           12 :                 },
   11322           12 :                 PersistentLayerKey {
   11323           12 :                     key_range: get_key(5)..get_key(7),
   11324           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11325           12 :                     is_delta: true,
   11326           12 :                 },
   11327           12 :                 PersistentLayerKey {
   11328           12 :                     key_range: get_key(8)..get_key(10),
   11329           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11330           12 :                     is_delta: true,
   11331           12 :                 },
   11332           12 :             ],
   11333           12 :         );
   11334           12 : 
   11335           12 :         // Do a partial compaction on key range 2..4
   11336           12 :         tline
   11337           12 :             .compact_with_gc(
   11338           12 :                 &cancel,
   11339           12 :                 CompactOptions {
   11340           12 :                     flags: EnumSet::new(),
   11341           12 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11342           12 :                     ..Default::default()
   11343           12 :                 },
   11344           12 :                 &ctx,
   11345           12 :             )
   11346           12 :             .await
   11347           12 :             .unwrap();
   11348           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11349           12 :         check_layer_map_key_eq(
   11350           12 :             all_layers,
   11351           12 :             vec![
   11352           12 :                 PersistentLayerKey {
   11353           12 :                     key_range: get_key(0)..get_key(2),
   11354           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11355           12 :                     is_delta: false,
   11356           12 :                 },
   11357           12 :                 PersistentLayerKey {
   11358           12 :                     key_range: get_key(0)..get_key(10),
   11359           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11360           12 :                     is_delta: false,
   11361           12 :                 },
   11362           12 :                 // image layer generated for the compaction range 2-4
   11363           12 :                 PersistentLayerKey {
   11364           12 :                     key_range: get_key(2)..get_key(4),
   11365           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11366           12 :                     is_delta: false,
   11367           12 :                 },
   11368           12 :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11369           12 :                 PersistentLayerKey {
   11370           12 :                     key_range: get_key(2)..get_key(4),
   11371           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11372           12 :                     is_delta: true,
   11373           12 :                 },
   11374           12 :                 PersistentLayerKey {
   11375           12 :                     key_range: get_key(5)..get_key(7),
   11376           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11377           12 :                     is_delta: true,
   11378           12 :                 },
   11379           12 :                 PersistentLayerKey {
   11380           12 :                     key_range: get_key(8)..get_key(10),
   11381           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11382           12 :                     is_delta: true,
   11383           12 :                 },
   11384           12 :             ],
   11385           12 :         );
   11386           12 : 
   11387           12 :         // Do a partial compaction on key range 4..9
   11388           12 :         tline
   11389           12 :             .compact_with_gc(
   11390           12 :                 &cancel,
   11391           12 :                 CompactOptions {
   11392           12 :                     flags: EnumSet::new(),
   11393           12 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11394           12 :                     ..Default::default()
   11395           12 :                 },
   11396           12 :                 &ctx,
   11397           12 :             )
   11398           12 :             .await
   11399           12 :             .unwrap();
   11400           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11401           12 :         check_layer_map_key_eq(
   11402           12 :             all_layers,
   11403           12 :             vec![
   11404           12 :                 PersistentLayerKey {
   11405           12 :                     key_range: get_key(0)..get_key(2),
   11406           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11407           12 :                     is_delta: false,
   11408           12 :                 },
   11409           12 :                 PersistentLayerKey {
   11410           12 :                     key_range: get_key(0)..get_key(10),
   11411           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11412           12 :                     is_delta: false,
   11413           12 :                 },
   11414           12 :                 PersistentLayerKey {
   11415           12 :                     key_range: get_key(2)..get_key(4),
   11416           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11417           12 :                     is_delta: false,
   11418           12 :                 },
   11419           12 :                 PersistentLayerKey {
   11420           12 :                     key_range: get_key(2)..get_key(4),
   11421           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11422           12 :                     is_delta: true,
   11423           12 :                 },
   11424           12 :                 // image layer generated for this compaction range
   11425           12 :                 PersistentLayerKey {
   11426           12 :                     key_range: get_key(4)..get_key(9),
   11427           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11428           12 :                     is_delta: false,
   11429           12 :                 },
   11430           12 :                 PersistentLayerKey {
   11431           12 :                     key_range: get_key(8)..get_key(10),
   11432           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11433           12 :                     is_delta: true,
   11434           12 :                 },
   11435           12 :             ],
   11436           12 :         );
   11437           12 : 
   11438           12 :         // Do a partial compaction on key range 9..10
   11439           12 :         tline
   11440           12 :             .compact_with_gc(
   11441           12 :                 &cancel,
   11442           12 :                 CompactOptions {
   11443           12 :                     flags: EnumSet::new(),
   11444           12 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11445           12 :                     ..Default::default()
   11446           12 :                 },
   11447           12 :                 &ctx,
   11448           12 :             )
   11449           12 :             .await
   11450           12 :             .unwrap();
   11451           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11452           12 :         check_layer_map_key_eq(
   11453           12 :             all_layers,
   11454           12 :             vec![
   11455           12 :                 PersistentLayerKey {
   11456           12 :                     key_range: get_key(0)..get_key(2),
   11457           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11458           12 :                     is_delta: false,
   11459           12 :                 },
   11460           12 :                 PersistentLayerKey {
   11461           12 :                     key_range: get_key(0)..get_key(10),
   11462           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11463           12 :                     is_delta: false,
   11464           12 :                 },
   11465           12 :                 PersistentLayerKey {
   11466           12 :                     key_range: get_key(2)..get_key(4),
   11467           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11468           12 :                     is_delta: false,
   11469           12 :                 },
   11470           12 :                 PersistentLayerKey {
   11471           12 :                     key_range: get_key(2)..get_key(4),
   11472           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11473           12 :                     is_delta: true,
   11474           12 :                 },
   11475           12 :                 PersistentLayerKey {
   11476           12 :                     key_range: get_key(4)..get_key(9),
   11477           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11478           12 :                     is_delta: false,
   11479           12 :                 },
   11480           12 :                 // image layer generated for the compaction range
   11481           12 :                 PersistentLayerKey {
   11482           12 :                     key_range: get_key(9)..get_key(10),
   11483           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11484           12 :                     is_delta: false,
   11485           12 :                 },
   11486           12 :                 PersistentLayerKey {
   11487           12 :                     key_range: get_key(8)..get_key(10),
   11488           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11489           12 :                     is_delta: true,
   11490           12 :                 },
   11491           12 :             ],
   11492           12 :         );
   11493           12 : 
   11494           12 :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11495           12 :         tline
   11496           12 :             .compact_with_gc(
   11497           12 :                 &cancel,
   11498           12 :                 CompactOptions {
   11499           12 :                     flags: EnumSet::new(),
   11500           12 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11501           12 :                     ..Default::default()
   11502           12 :                 },
   11503           12 :                 &ctx,
   11504           12 :             )
   11505           12 :             .await
   11506           12 :             .unwrap();
   11507           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11508           12 :         check_layer_map_key_eq(
   11509           12 :             all_layers,
   11510           12 :             vec![
   11511           12 :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11512           12 :                 PersistentLayerKey {
   11513           12 :                     key_range: get_key(0)..get_key(10),
   11514           12 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11515           12 :                     is_delta: false,
   11516           12 :                 },
   11517           12 :                 PersistentLayerKey {
   11518           12 :                     key_range: get_key(2)..get_key(4),
   11519           12 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11520           12 :                     is_delta: true,
   11521           12 :                 },
   11522           12 :                 PersistentLayerKey {
   11523           12 :                     key_range: get_key(8)..get_key(10),
   11524           12 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11525           12 :                     is_delta: true,
   11526           12 :                 },
   11527           12 :             ],
   11528           12 :         );
   11529           12 :         Ok(())
   11530           12 :     }
   11531              : 
   11532              :     #[cfg(feature = "testing")]
   11533              :     #[tokio::test]
   11534           12 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11535           12 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11536           12 :             .await
   11537           12 :             .unwrap();
   11538           12 :         let (tenant, ctx) = harness.load().await;
   11539           12 :         let tline_parent = tenant
   11540           12 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11541           12 :             .await
   11542           12 :             .unwrap();
   11543           12 :         let tline_child = tenant
   11544           12 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11545           12 :             .await
   11546           12 :             .unwrap();
   11547           12 :         {
   11548           12 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11549           12 :             assert_eq!(
   11550           12 :                 gc_info_parent.retain_lsns,
   11551           12 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11552           12 :             );
   11553           12 :         }
   11554           12 :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11555           12 :         tline_child
   11556           12 :             .remote_client
   11557           12 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11558           12 :             .unwrap();
   11559           12 :         tline_child.remote_client.wait_completion().await.unwrap();
   11560           12 :         offload_timeline(&tenant, &tline_child)
   11561           12 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11562           12 :             .await.unwrap();
   11563           12 :         let child_timeline_id = tline_child.timeline_id;
   11564           12 :         Arc::try_unwrap(tline_child).unwrap();
   11565           12 : 
   11566           12 :         {
   11567           12 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11568           12 :             assert_eq!(
   11569           12 :                 gc_info_parent.retain_lsns,
   11570           12 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11571           12 :             );
   11572           12 :         }
   11573           12 : 
   11574           12 :         tenant
   11575           12 :             .get_offloaded_timeline(child_timeline_id)
   11576           12 :             .unwrap()
   11577           12 :             .defuse_for_tenant_drop();
   11578           12 : 
   11579           12 :         Ok(())
   11580           12 :     }
   11581              : 
   11582              :     #[cfg(feature = "testing")]
   11583              :     #[tokio::test]
   11584           12 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11585           12 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11586           12 :         let (tenant, ctx) = harness.load().await;
   11587           12 : 
   11588         1776 :         fn get_key(id: u32) -> Key {
   11589         1776 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11590         1776 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11591         1776 :             key.field6 = id;
   11592         1776 :             key
   11593         1776 :         }
   11594           12 : 
   11595           12 :         let img_layer = (0..10)
   11596          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11597           12 :             .collect_vec();
   11598           12 : 
   11599           12 :         let delta1 = vec![(
   11600           12 :             get_key(1),
   11601           12 :             Lsn(0x20),
   11602           12 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11603           12 :         )];
   11604           12 :         let delta4 = vec![(
   11605           12 :             get_key(1),
   11606           12 :             Lsn(0x28),
   11607           12 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11608           12 :         )];
   11609           12 :         let delta2 = vec![
   11610           12 :             (
   11611           12 :                 get_key(1),
   11612           12 :                 Lsn(0x30),
   11613           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11614           12 :             ),
   11615           12 :             (
   11616           12 :                 get_key(1),
   11617           12 :                 Lsn(0x38),
   11618           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11619           12 :             ),
   11620           12 :         ];
   11621           12 :         let delta3 = vec![
   11622           12 :             (
   11623           12 :                 get_key(8),
   11624           12 :                 Lsn(0x48),
   11625           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11626           12 :             ),
   11627           12 :             (
   11628           12 :                 get_key(9),
   11629           12 :                 Lsn(0x48),
   11630           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11631           12 :             ),
   11632           12 :         ];
   11633           12 : 
   11634           12 :         let tline = tenant
   11635           12 :             .create_test_timeline_with_layers(
   11636           12 :                 TIMELINE_ID,
   11637           12 :                 Lsn(0x10),
   11638           12 :                 DEFAULT_PG_VERSION,
   11639           12 :                 &ctx,
   11640           12 :                 vec![], // in-memory layers
   11641           12 :                 vec![
   11642           12 :                     // delta1/2/4 only contain a single key but multiple updates
   11643           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11644           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11645           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11646           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11647           12 :                 ], // delta layers
   11648           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11649           12 :                 Lsn(0x50),
   11650           12 :             )
   11651           12 :             .await?;
   11652           12 :         {
   11653           12 :             tline
   11654           12 :                 .applied_gc_cutoff_lsn
   11655           12 :                 .lock_for_write()
   11656           12 :                 .store_and_unlock(Lsn(0x30))
   11657           12 :                 .wait()
   11658           12 :                 .await;
   11659           12 :             // Update GC info
   11660           12 :             let mut guard = tline.gc_info.write().unwrap();
   11661           12 :             *guard = GcInfo {
   11662           12 :                 retain_lsns: vec![
   11663           12 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11664           12 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11665           12 :                 ],
   11666           12 :                 cutoffs: GcCutoffs {
   11667           12 :                     time: Lsn(0x30),
   11668           12 :                     space: Lsn(0x30),
   11669           12 :                 },
   11670           12 :                 leases: Default::default(),
   11671           12 :                 within_ancestor_pitr: false,
   11672           12 :             };
   11673           12 :         }
   11674           12 : 
   11675           12 :         let expected_result = [
   11676           12 :             Bytes::from_static(b"value 0@0x10"),
   11677           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11678           12 :             Bytes::from_static(b"value 2@0x10"),
   11679           12 :             Bytes::from_static(b"value 3@0x10"),
   11680           12 :             Bytes::from_static(b"value 4@0x10"),
   11681           12 :             Bytes::from_static(b"value 5@0x10"),
   11682           12 :             Bytes::from_static(b"value 6@0x10"),
   11683           12 :             Bytes::from_static(b"value 7@0x10"),
   11684           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11685           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11686           12 :         ];
   11687           12 : 
   11688           12 :         let expected_result_at_gc_horizon = [
   11689           12 :             Bytes::from_static(b"value 0@0x10"),
   11690           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11691           12 :             Bytes::from_static(b"value 2@0x10"),
   11692           12 :             Bytes::from_static(b"value 3@0x10"),
   11693           12 :             Bytes::from_static(b"value 4@0x10"),
   11694           12 :             Bytes::from_static(b"value 5@0x10"),
   11695           12 :             Bytes::from_static(b"value 6@0x10"),
   11696           12 :             Bytes::from_static(b"value 7@0x10"),
   11697           12 :             Bytes::from_static(b"value 8@0x10"),
   11698           12 :             Bytes::from_static(b"value 9@0x10"),
   11699           12 :         ];
   11700           12 : 
   11701           12 :         let expected_result_at_lsn_20 = [
   11702           12 :             Bytes::from_static(b"value 0@0x10"),
   11703           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11704           12 :             Bytes::from_static(b"value 2@0x10"),
   11705           12 :             Bytes::from_static(b"value 3@0x10"),
   11706           12 :             Bytes::from_static(b"value 4@0x10"),
   11707           12 :             Bytes::from_static(b"value 5@0x10"),
   11708           12 :             Bytes::from_static(b"value 6@0x10"),
   11709           12 :             Bytes::from_static(b"value 7@0x10"),
   11710           12 :             Bytes::from_static(b"value 8@0x10"),
   11711           12 :             Bytes::from_static(b"value 9@0x10"),
   11712           12 :         ];
   11713           12 : 
   11714           12 :         let expected_result_at_lsn_10 = [
   11715           12 :             Bytes::from_static(b"value 0@0x10"),
   11716           12 :             Bytes::from_static(b"value 1@0x10"),
   11717           12 :             Bytes::from_static(b"value 2@0x10"),
   11718           12 :             Bytes::from_static(b"value 3@0x10"),
   11719           12 :             Bytes::from_static(b"value 4@0x10"),
   11720           12 :             Bytes::from_static(b"value 5@0x10"),
   11721           12 :             Bytes::from_static(b"value 6@0x10"),
   11722           12 :             Bytes::from_static(b"value 7@0x10"),
   11723           12 :             Bytes::from_static(b"value 8@0x10"),
   11724           12 :             Bytes::from_static(b"value 9@0x10"),
   11725           12 :         ];
   11726           12 : 
   11727           36 :         let verify_result = || async {
   11728           36 :             let gc_horizon = {
   11729           36 :                 let gc_info = tline.gc_info.read().unwrap();
   11730           36 :                 gc_info.cutoffs.time
   11731           12 :             };
   11732          396 :             for idx in 0..10 {
   11733          360 :                 assert_eq!(
   11734          360 :                     tline
   11735          360 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11736          360 :                         .await
   11737          360 :                         .unwrap(),
   11738          360 :                     &expected_result[idx]
   11739           12 :                 );
   11740          360 :                 assert_eq!(
   11741          360 :                     tline
   11742          360 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11743          360 :                         .await
   11744          360 :                         .unwrap(),
   11745          360 :                     &expected_result_at_gc_horizon[idx]
   11746           12 :                 );
   11747          360 :                 assert_eq!(
   11748          360 :                     tline
   11749          360 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   11750          360 :                         .await
   11751          360 :                         .unwrap(),
   11752          360 :                     &expected_result_at_lsn_20[idx]
   11753           12 :                 );
   11754          360 :                 assert_eq!(
   11755          360 :                     tline
   11756          360 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   11757          360 :                         .await
   11758          360 :                         .unwrap(),
   11759          360 :                     &expected_result_at_lsn_10[idx]
   11760           12 :                 );
   11761           12 :             }
   11762           72 :         };
   11763           12 : 
   11764           12 :         verify_result().await;
   11765           12 : 
   11766           12 :         let cancel = CancellationToken::new();
   11767           12 :         tline
   11768           12 :             .compact_with_gc(
   11769           12 :                 &cancel,
   11770           12 :                 CompactOptions {
   11771           12 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   11772           12 :                     ..Default::default()
   11773           12 :                 },
   11774           12 :                 &ctx,
   11775           12 :             )
   11776           12 :             .await
   11777           12 :             .unwrap();
   11778           12 :         verify_result().await;
   11779           12 : 
   11780           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11781           12 :         check_layer_map_key_eq(
   11782           12 :             all_layers,
   11783           12 :             vec![
   11784           12 :                 // The original image layer, not compacted
   11785           12 :                 PersistentLayerKey {
   11786           12 :                     key_range: get_key(0)..get_key(10),
   11787           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11788           12 :                     is_delta: false,
   11789           12 :                 },
   11790           12 :                 // Delta layer below the specified above_lsn not compacted
   11791           12 :                 PersistentLayerKey {
   11792           12 :                     key_range: get_key(1)..get_key(2),
   11793           12 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   11794           12 :                     is_delta: true,
   11795           12 :                 },
   11796           12 :                 // Delta layer compacted above the LSN
   11797           12 :                 PersistentLayerKey {
   11798           12 :                     key_range: get_key(1)..get_key(10),
   11799           12 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   11800           12 :                     is_delta: true,
   11801           12 :                 },
   11802           12 :             ],
   11803           12 :         );
   11804           12 : 
   11805           12 :         // compact again
   11806           12 :         tline
   11807           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   11808           12 :             .await
   11809           12 :             .unwrap();
   11810           12 :         verify_result().await;
   11811           12 : 
   11812           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11813           12 :         check_layer_map_key_eq(
   11814           12 :             all_layers,
   11815           12 :             vec![
   11816           12 :                 // The compacted image layer (full key range)
   11817           12 :                 PersistentLayerKey {
   11818           12 :                     key_range: Key::MIN..Key::MAX,
   11819           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11820           12 :                     is_delta: false,
   11821           12 :                 },
   11822           12 :                 // All other data in the delta layer
   11823           12 :                 PersistentLayerKey {
   11824           12 :                     key_range: get_key(1)..get_key(10),
   11825           12 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   11826           12 :                     is_delta: true,
   11827           12 :                 },
   11828           12 :             ],
   11829           12 :         );
   11830           12 : 
   11831           12 :         Ok(())
   11832           12 :     }
   11833              : 
   11834              :     #[cfg(feature = "testing")]
   11835              :     #[tokio::test]
   11836           12 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   11837           12 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   11838           12 :         let (tenant, ctx) = harness.load().await;
   11839           12 : 
   11840         3048 :         fn get_key(id: u32) -> Key {
   11841         3048 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11842         3048 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11843         3048 :             key.field6 = id;
   11844         3048 :             key
   11845         3048 :         }
   11846           12 : 
   11847           12 :         let img_layer = (0..10)
   11848          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11849           12 :             .collect_vec();
   11850           12 : 
   11851           12 :         let delta1 = vec![(
   11852           12 :             get_key(1),
   11853           12 :             Lsn(0x20),
   11854           12 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11855           12 :         )];
   11856           12 :         let delta4 = vec![(
   11857           12 :             get_key(1),
   11858           12 :             Lsn(0x28),
   11859           12 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11860           12 :         )];
   11861           12 :         let delta2 = vec![
   11862           12 :             (
   11863           12 :                 get_key(1),
   11864           12 :                 Lsn(0x30),
   11865           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11866           12 :             ),
   11867           12 :             (
   11868           12 :                 get_key(1),
   11869           12 :                 Lsn(0x38),
   11870           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11871           12 :             ),
   11872           12 :         ];
   11873           12 :         let delta3 = vec![
   11874           12 :             (
   11875           12 :                 get_key(8),
   11876           12 :                 Lsn(0x48),
   11877           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11878           12 :             ),
   11879           12 :             (
   11880           12 :                 get_key(9),
   11881           12 :                 Lsn(0x48),
   11882           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11883           12 :             ),
   11884           12 :         ];
   11885           12 : 
   11886           12 :         let tline = tenant
   11887           12 :             .create_test_timeline_with_layers(
   11888           12 :                 TIMELINE_ID,
   11889           12 :                 Lsn(0x10),
   11890           12 :                 DEFAULT_PG_VERSION,
   11891           12 :                 &ctx,
   11892           12 :                 vec![], // in-memory layers
   11893           12 :                 vec![
   11894           12 :                     // delta1/2/4 only contain a single key but multiple updates
   11895           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11896           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11897           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11898           12 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11899           12 :                 ], // delta layers
   11900           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11901           12 :                 Lsn(0x50),
   11902           12 :             )
   11903           12 :             .await?;
   11904           12 :         {
   11905           12 :             tline
   11906           12 :                 .applied_gc_cutoff_lsn
   11907           12 :                 .lock_for_write()
   11908           12 :                 .store_and_unlock(Lsn(0x30))
   11909           12 :                 .wait()
   11910           12 :                 .await;
   11911           12 :             // Update GC info
   11912           12 :             let mut guard = tline.gc_info.write().unwrap();
   11913           12 :             *guard = GcInfo {
   11914           12 :                 retain_lsns: vec![
   11915           12 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11916           12 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11917           12 :                 ],
   11918           12 :                 cutoffs: GcCutoffs {
   11919           12 :                     time: Lsn(0x30),
   11920           12 :                     space: Lsn(0x30),
   11921           12 :                 },
   11922           12 :                 leases: Default::default(),
   11923           12 :                 within_ancestor_pitr: false,
   11924           12 :             };
   11925           12 :         }
   11926           12 : 
   11927           12 :         let expected_result = [
   11928           12 :             Bytes::from_static(b"value 0@0x10"),
   11929           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11930           12 :             Bytes::from_static(b"value 2@0x10"),
   11931           12 :             Bytes::from_static(b"value 3@0x10"),
   11932           12 :             Bytes::from_static(b"value 4@0x10"),
   11933           12 :             Bytes::from_static(b"value 5@0x10"),
   11934           12 :             Bytes::from_static(b"value 6@0x10"),
   11935           12 :             Bytes::from_static(b"value 7@0x10"),
   11936           12 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11937           12 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11938           12 :         ];
   11939           12 : 
   11940           12 :         let expected_result_at_gc_horizon = [
   11941           12 :             Bytes::from_static(b"value 0@0x10"),
   11942           12 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11943           12 :             Bytes::from_static(b"value 2@0x10"),
   11944           12 :             Bytes::from_static(b"value 3@0x10"),
   11945           12 :             Bytes::from_static(b"value 4@0x10"),
   11946           12 :             Bytes::from_static(b"value 5@0x10"),
   11947           12 :             Bytes::from_static(b"value 6@0x10"),
   11948           12 :             Bytes::from_static(b"value 7@0x10"),
   11949           12 :             Bytes::from_static(b"value 8@0x10"),
   11950           12 :             Bytes::from_static(b"value 9@0x10"),
   11951           12 :         ];
   11952           12 : 
   11953           12 :         let expected_result_at_lsn_20 = [
   11954           12 :             Bytes::from_static(b"value 0@0x10"),
   11955           12 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11956           12 :             Bytes::from_static(b"value 2@0x10"),
   11957           12 :             Bytes::from_static(b"value 3@0x10"),
   11958           12 :             Bytes::from_static(b"value 4@0x10"),
   11959           12 :             Bytes::from_static(b"value 5@0x10"),
   11960           12 :             Bytes::from_static(b"value 6@0x10"),
   11961           12 :             Bytes::from_static(b"value 7@0x10"),
   11962           12 :             Bytes::from_static(b"value 8@0x10"),
   11963           12 :             Bytes::from_static(b"value 9@0x10"),
   11964           12 :         ];
   11965           12 : 
   11966           12 :         let expected_result_at_lsn_10 = [
   11967           12 :             Bytes::from_static(b"value 0@0x10"),
   11968           12 :             Bytes::from_static(b"value 1@0x10"),
   11969           12 :             Bytes::from_static(b"value 2@0x10"),
   11970           12 :             Bytes::from_static(b"value 3@0x10"),
   11971           12 :             Bytes::from_static(b"value 4@0x10"),
   11972           12 :             Bytes::from_static(b"value 5@0x10"),
   11973           12 :             Bytes::from_static(b"value 6@0x10"),
   11974           12 :             Bytes::from_static(b"value 7@0x10"),
   11975           12 :             Bytes::from_static(b"value 8@0x10"),
   11976           12 :             Bytes::from_static(b"value 9@0x10"),
   11977           12 :         ];
   11978           12 : 
   11979           60 :         let verify_result = || async {
   11980           60 :             let gc_horizon = {
   11981           60 :                 let gc_info = tline.gc_info.read().unwrap();
   11982           60 :                 gc_info.cutoffs.time
   11983           12 :             };
   11984          660 :             for idx in 0..10 {
   11985          600 :                 assert_eq!(
   11986          600 :                     tline
   11987          600 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   11988          600 :                         .await
   11989          600 :                         .unwrap(),
   11990          600 :                     &expected_result[idx]
   11991           12 :                 );
   11992          600 :                 assert_eq!(
   11993          600 :                     tline
   11994          600 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   11995          600 :                         .await
   11996          600 :                         .unwrap(),
   11997          600 :                     &expected_result_at_gc_horizon[idx]
   11998           12 :                 );
   11999          600 :                 assert_eq!(
   12000          600 :                     tline
   12001          600 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12002          600 :                         .await
   12003          600 :                         .unwrap(),
   12004          600 :                     &expected_result_at_lsn_20[idx]
   12005           12 :                 );
   12006          600 :                 assert_eq!(
   12007          600 :                     tline
   12008          600 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12009          600 :                         .await
   12010          600 :                         .unwrap(),
   12011          600 :                     &expected_result_at_lsn_10[idx]
   12012           12 :                 );
   12013           12 :             }
   12014          120 :         };
   12015           12 : 
   12016           12 :         verify_result().await;
   12017           12 : 
   12018           12 :         let cancel = CancellationToken::new();
   12019           12 : 
   12020           12 :         tline
   12021           12 :             .compact_with_gc(
   12022           12 :                 &cancel,
   12023           12 :                 CompactOptions {
   12024           12 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   12025           12 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   12026           12 :                     ..Default::default()
   12027           12 :                 },
   12028           12 :                 &ctx,
   12029           12 :             )
   12030           12 :             .await
   12031           12 :             .unwrap();
   12032           12 :         verify_result().await;
   12033           12 : 
   12034           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12035           12 :         check_layer_map_key_eq(
   12036           12 :             all_layers,
   12037           12 :             vec![
   12038           12 :                 // The original image layer, not compacted
   12039           12 :                 PersistentLayerKey {
   12040           12 :                     key_range: get_key(0)..get_key(10),
   12041           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12042           12 :                     is_delta: false,
   12043           12 :                 },
   12044           12 :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   12045           12 :                 // the layer 0x28-0x30 into one.
   12046           12 :                 PersistentLayerKey {
   12047           12 :                     key_range: get_key(1)..get_key(2),
   12048           12 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12049           12 :                     is_delta: true,
   12050           12 :                 },
   12051           12 :                 // Above the upper bound and untouched
   12052           12 :                 PersistentLayerKey {
   12053           12 :                     key_range: get_key(1)..get_key(2),
   12054           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12055           12 :                     is_delta: true,
   12056           12 :                 },
   12057           12 :                 // This layer is untouched
   12058           12 :                 PersistentLayerKey {
   12059           12 :                     key_range: get_key(8)..get_key(10),
   12060           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12061           12 :                     is_delta: true,
   12062           12 :                 },
   12063           12 :             ],
   12064           12 :         );
   12065           12 : 
   12066           12 :         tline
   12067           12 :             .compact_with_gc(
   12068           12 :                 &cancel,
   12069           12 :                 CompactOptions {
   12070           12 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12071           12 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12072           12 :                     ..Default::default()
   12073           12 :                 },
   12074           12 :                 &ctx,
   12075           12 :             )
   12076           12 :             .await
   12077           12 :             .unwrap();
   12078           12 :         verify_result().await;
   12079           12 : 
   12080           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12081           12 :         check_layer_map_key_eq(
   12082           12 :             all_layers,
   12083           12 :             vec![
   12084           12 :                 // The original image layer, not compacted
   12085           12 :                 PersistentLayerKey {
   12086           12 :                     key_range: get_key(0)..get_key(10),
   12087           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12088           12 :                     is_delta: false,
   12089           12 :                 },
   12090           12 :                 // Not in the compaction key range, uncompacted
   12091           12 :                 PersistentLayerKey {
   12092           12 :                     key_range: get_key(1)..get_key(2),
   12093           12 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12094           12 :                     is_delta: true,
   12095           12 :                 },
   12096           12 :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12097           12 :                 PersistentLayerKey {
   12098           12 :                     key_range: get_key(1)..get_key(2),
   12099           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12100           12 :                     is_delta: true,
   12101           12 :                 },
   12102           12 :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12103           12 :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12104           12 :                 // becomes 0x50.
   12105           12 :                 PersistentLayerKey {
   12106           12 :                     key_range: get_key(8)..get_key(10),
   12107           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12108           12 :                     is_delta: true,
   12109           12 :                 },
   12110           12 :             ],
   12111           12 :         );
   12112           12 : 
   12113           12 :         // compact again
   12114           12 :         tline
   12115           12 :             .compact_with_gc(
   12116           12 :                 &cancel,
   12117           12 :                 CompactOptions {
   12118           12 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12119           12 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12120           12 :                     ..Default::default()
   12121           12 :                 },
   12122           12 :                 &ctx,
   12123           12 :             )
   12124           12 :             .await
   12125           12 :             .unwrap();
   12126           12 :         verify_result().await;
   12127           12 : 
   12128           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12129           12 :         check_layer_map_key_eq(
   12130           12 :             all_layers,
   12131           12 :             vec![
   12132           12 :                 // The original image layer, not compacted
   12133           12 :                 PersistentLayerKey {
   12134           12 :                     key_range: get_key(0)..get_key(10),
   12135           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12136           12 :                     is_delta: false,
   12137           12 :                 },
   12138           12 :                 // The range gets compacted
   12139           12 :                 PersistentLayerKey {
   12140           12 :                     key_range: get_key(1)..get_key(2),
   12141           12 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12142           12 :                     is_delta: true,
   12143           12 :                 },
   12144           12 :                 // Not touched during this iteration of compaction
   12145           12 :                 PersistentLayerKey {
   12146           12 :                     key_range: get_key(8)..get_key(10),
   12147           12 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12148           12 :                     is_delta: true,
   12149           12 :                 },
   12150           12 :             ],
   12151           12 :         );
   12152           12 : 
   12153           12 :         // final full compaction
   12154           12 :         tline
   12155           12 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12156           12 :             .await
   12157           12 :             .unwrap();
   12158           12 :         verify_result().await;
   12159           12 : 
   12160           12 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12161           12 :         check_layer_map_key_eq(
   12162           12 :             all_layers,
   12163           12 :             vec![
   12164           12 :                 // The compacted image layer (full key range)
   12165           12 :                 PersistentLayerKey {
   12166           12 :                     key_range: Key::MIN..Key::MAX,
   12167           12 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12168           12 :                     is_delta: false,
   12169           12 :                 },
   12170           12 :                 // All other data in the delta layer
   12171           12 :                 PersistentLayerKey {
   12172           12 :                     key_range: get_key(1)..get_key(10),
   12173           12 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12174           12 :                     is_delta: true,
   12175           12 :                 },
   12176           12 :             ],
   12177           12 :         );
   12178           12 : 
   12179           12 :         Ok(())
   12180           12 :     }
   12181              : 
   12182              :     #[cfg(feature = "testing")]
   12183              :     #[tokio::test]
   12184           12 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12185           12 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12186           12 :         let (tenant, ctx) = harness.load().await;
   12187           12 : 
   12188          156 :         fn get_key(id: u32) -> Key {
   12189          156 :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12190          156 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12191          156 :             key.field6 = id;
   12192          156 :             key
   12193          156 :         }
   12194           12 : 
   12195           12 :         let img_layer = (0..10)
   12196          120 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12197           12 :             .collect_vec();
   12198           12 : 
   12199           12 :         let delta1 = vec![
   12200           12 :             (
   12201           12 :                 get_key(1),
   12202           12 :                 Lsn(0x20),
   12203           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12204           12 :             ),
   12205           12 :             (
   12206           12 :                 get_key(1),
   12207           12 :                 Lsn(0x24),
   12208           12 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12209           12 :             ),
   12210           12 :             (
   12211           12 :                 get_key(1),
   12212           12 :                 Lsn(0x28),
   12213           12 :                 // This record will fail to redo
   12214           12 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12215           12 :             ),
   12216           12 :         ];
   12217           12 : 
   12218           12 :         let tline = tenant
   12219           12 :             .create_test_timeline_with_layers(
   12220           12 :                 TIMELINE_ID,
   12221           12 :                 Lsn(0x10),
   12222           12 :                 DEFAULT_PG_VERSION,
   12223           12 :                 &ctx,
   12224           12 :                 vec![], // in-memory layers
   12225           12 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12226           12 :                     Lsn(0x20)..Lsn(0x30),
   12227           12 :                     delta1,
   12228           12 :                 )], // delta layers
   12229           12 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12230           12 :                 Lsn(0x50),
   12231           12 :             )
   12232           12 :             .await?;
   12233           12 :         {
   12234           12 :             tline
   12235           12 :                 .applied_gc_cutoff_lsn
   12236           12 :                 .lock_for_write()
   12237           12 :                 .store_and_unlock(Lsn(0x30))
   12238           12 :                 .wait()
   12239           12 :                 .await;
   12240           12 :             // Update GC info
   12241           12 :             let mut guard = tline.gc_info.write().unwrap();
   12242           12 :             *guard = GcInfo {
   12243           12 :                 retain_lsns: vec![],
   12244           12 :                 cutoffs: GcCutoffs {
   12245           12 :                     time: Lsn(0x30),
   12246           12 :                     space: Lsn(0x30),
   12247           12 :                 },
   12248           12 :                 leases: Default::default(),
   12249           12 :                 within_ancestor_pitr: false,
   12250           12 :             };
   12251           12 :         }
   12252           12 : 
   12253           12 :         let cancel = CancellationToken::new();
   12254           12 : 
   12255           12 :         // Compaction will fail, but should not fire any critical error.
   12256           12 :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12257           12 :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12258           12 :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12259           12 :         let res = tline
   12260           12 :             .compact_with_gc(
   12261           12 :                 &cancel,
   12262           12 :                 CompactOptions {
   12263           12 :                     compact_key_range: None,
   12264           12 :                     compact_lsn_range: None,
   12265           12 :                     ..Default::default()
   12266           12 :                 },
   12267           12 :                 &ctx,
   12268           12 :             )
   12269           12 :             .await;
   12270           12 :         assert!(res.is_err());
   12271           12 : 
   12272           12 :         Ok(())
   12273           12 :     }
   12274              : 
   12275              :     #[cfg(feature = "testing")]
   12276              :     #[tokio::test]
   12277           12 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12278           12 :         use pageserver_api::models::TimelineVisibilityState;
   12279           12 : 
   12280           12 :         use crate::tenant::size::gather_inputs;
   12281           12 : 
   12282           12 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12283           12 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12284           12 :             pitr_interval: Some(Duration::ZERO),
   12285           12 :             ..Default::default()
   12286           12 :         };
   12287           12 :         let harness = TenantHarness::create_custom(
   12288           12 :             "test_synthetic_size_calculation_with_invisible_branches",
   12289           12 :             tenant_conf,
   12290           12 :             TenantId::generate(),
   12291           12 :             ShardIdentity::unsharded(),
   12292           12 :             Generation::new(0xdeadbeef),
   12293           12 :         )
   12294           12 :         .await?;
   12295           12 :         let (tenant, ctx) = harness.load().await;
   12296           12 :         let main_tline = tenant
   12297           12 :             .create_test_timeline_with_layers(
   12298           12 :                 TIMELINE_ID,
   12299           12 :                 Lsn(0x10),
   12300           12 :                 DEFAULT_PG_VERSION,
   12301           12 :                 &ctx,
   12302           12 :                 vec![],
   12303           12 :                 vec![],
   12304           12 :                 vec![],
   12305           12 :                 Lsn(0x100),
   12306           12 :             )
   12307           12 :             .await?;
   12308           12 : 
   12309           12 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12310           12 :         tenant
   12311           12 :             .branch_timeline_test_with_layers(
   12312           12 :                 &main_tline,
   12313           12 :                 snapshot1,
   12314           12 :                 Some(Lsn(0x20)),
   12315           12 :                 &ctx,
   12316           12 :                 vec![],
   12317           12 :                 vec![],
   12318           12 :                 Lsn(0x50),
   12319           12 :             )
   12320           12 :             .await?;
   12321           12 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12322           12 :         tenant
   12323           12 :             .branch_timeline_test_with_layers(
   12324           12 :                 &main_tline,
   12325           12 :                 snapshot2,
   12326           12 :                 Some(Lsn(0x30)),
   12327           12 :                 &ctx,
   12328           12 :                 vec![],
   12329           12 :                 vec![],
   12330           12 :                 Lsn(0x50),
   12331           12 :             )
   12332           12 :             .await?;
   12333           12 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12334           12 :         tenant
   12335           12 :             .branch_timeline_test_with_layers(
   12336           12 :                 &main_tline,
   12337           12 :                 snapshot3,
   12338           12 :                 Some(Lsn(0x40)),
   12339           12 :                 &ctx,
   12340           12 :                 vec![],
   12341           12 :                 vec![],
   12342           12 :                 Lsn(0x50),
   12343           12 :             )
   12344           12 :             .await?;
   12345           12 :         let limit = Arc::new(Semaphore::new(1));
   12346           12 :         let max_retention_period = None;
   12347           12 :         let mut logical_size_cache = HashMap::new();
   12348           12 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12349           12 :         let cancel = CancellationToken::new();
   12350           12 : 
   12351           12 :         let inputs = gather_inputs(
   12352           12 :             &tenant,
   12353           12 :             &limit,
   12354           12 :             max_retention_period,
   12355           12 :             &mut logical_size_cache,
   12356           12 :             cause,
   12357           12 :             &cancel,
   12358           12 :             &ctx,
   12359           12 :         )
   12360           12 :         .instrument(info_span!(
   12361           12 :             "gather_inputs",
   12362           12 :             tenant_id = "unknown",
   12363           12 :             shard_id = "unknown",
   12364           12 :         ))
   12365           12 :         .await?;
   12366           12 :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12367           12 :         use LsnKind::*;
   12368           12 :         use tenant_size_model::Segment;
   12369           12 :         let ModelInputs { mut segments, .. } = inputs;
   12370          180 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12371           72 :         for segment in segments.iter_mut() {
   12372           72 :             segment.segment.parent = None; // We don't care about the parent for the test
   12373           72 :             segment.segment.size = None; // We don't care about the size for the test
   12374           72 :         }
   12375           12 :         assert_eq!(
   12376           12 :             segments,
   12377           12 :             [
   12378           12 :                 SegmentMeta {
   12379           12 :                     segment: Segment {
   12380           12 :                         parent: None,
   12381           12 :                         lsn: 0x10,
   12382           12 :                         size: None,
   12383           12 :                         needed: false,
   12384           12 :                     },
   12385           12 :                     timeline_id: TIMELINE_ID,
   12386           12 :                     kind: BranchStart,
   12387           12 :                 },
   12388           12 :                 SegmentMeta {
   12389           12 :                     segment: Segment {
   12390           12 :                         parent: None,
   12391           12 :                         lsn: 0x20,
   12392           12 :                         size: None,
   12393           12 :                         needed: false,
   12394           12 :                     },
   12395           12 :                     timeline_id: TIMELINE_ID,
   12396           12 :                     kind: BranchPoint,
   12397           12 :                 },
   12398           12 :                 SegmentMeta {
   12399           12 :                     segment: Segment {
   12400           12 :                         parent: None,
   12401           12 :                         lsn: 0x30,
   12402           12 :                         size: None,
   12403           12 :                         needed: false,
   12404           12 :                     },
   12405           12 :                     timeline_id: TIMELINE_ID,
   12406           12 :                     kind: BranchPoint,
   12407           12 :                 },
   12408           12 :                 SegmentMeta {
   12409           12 :                     segment: Segment {
   12410           12 :                         parent: None,
   12411           12 :                         lsn: 0x40,
   12412           12 :                         size: None,
   12413           12 :                         needed: false,
   12414           12 :                     },
   12415           12 :                     timeline_id: TIMELINE_ID,
   12416           12 :                     kind: BranchPoint,
   12417           12 :                 },
   12418           12 :                 SegmentMeta {
   12419           12 :                     segment: Segment {
   12420           12 :                         parent: None,
   12421           12 :                         lsn: 0x100,
   12422           12 :                         size: None,
   12423           12 :                         needed: false,
   12424           12 :                     },
   12425           12 :                     timeline_id: TIMELINE_ID,
   12426           12 :                     kind: GcCutOff,
   12427           12 :                 }, // we need to retain everything above the last branch point
   12428           12 :                 SegmentMeta {
   12429           12 :                     segment: Segment {
   12430           12 :                         parent: None,
   12431           12 :                         lsn: 0x100,
   12432           12 :                         size: None,
   12433           12 :                         needed: true,
   12434           12 :                     },
   12435           12 :                     timeline_id: TIMELINE_ID,
   12436           12 :                     kind: BranchEnd,
   12437           12 :                 },
   12438           12 :             ]
   12439           12 :         );
   12440           12 : 
   12441           12 :         main_tline
   12442           12 :             .remote_client
   12443           12 :             .schedule_index_upload_for_timeline_invisible_state(
   12444           12 :                 TimelineVisibilityState::Invisible,
   12445           12 :             )?;
   12446           12 :         main_tline.remote_client.wait_completion().await?;
   12447           12 :         let inputs = gather_inputs(
   12448           12 :             &tenant,
   12449           12 :             &limit,
   12450           12 :             max_retention_period,
   12451           12 :             &mut logical_size_cache,
   12452           12 :             cause,
   12453           12 :             &cancel,
   12454           12 :             &ctx,
   12455           12 :         )
   12456           12 :         .instrument(info_span!(
   12457           12 :             "gather_inputs",
   12458           12 :             tenant_id = "unknown",
   12459           12 :             shard_id = "unknown",
   12460           12 :         ))
   12461           12 :         .await?;
   12462           12 :         let ModelInputs { mut segments, .. } = inputs;
   12463          168 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12464           60 :         for segment in segments.iter_mut() {
   12465           60 :             segment.segment.parent = None; // We don't care about the parent for the test
   12466           60 :             segment.segment.size = None; // We don't care about the size for the test
   12467           60 :         }
   12468           12 :         assert_eq!(
   12469           12 :             segments,
   12470           12 :             [
   12471           12 :                 SegmentMeta {
   12472           12 :                     segment: Segment {
   12473           12 :                         parent: None,
   12474           12 :                         lsn: 0x10,
   12475           12 :                         size: None,
   12476           12 :                         needed: false,
   12477           12 :                     },
   12478           12 :                     timeline_id: TIMELINE_ID,
   12479           12 :                     kind: BranchStart,
   12480           12 :                 },
   12481           12 :                 SegmentMeta {
   12482           12 :                     segment: Segment {
   12483           12 :                         parent: None,
   12484           12 :                         lsn: 0x20,
   12485           12 :                         size: None,
   12486           12 :                         needed: false,
   12487           12 :                     },
   12488           12 :                     timeline_id: TIMELINE_ID,
   12489           12 :                     kind: BranchPoint,
   12490           12 :                 },
   12491           12 :                 SegmentMeta {
   12492           12 :                     segment: Segment {
   12493           12 :                         parent: None,
   12494           12 :                         lsn: 0x30,
   12495           12 :                         size: None,
   12496           12 :                         needed: false,
   12497           12 :                     },
   12498           12 :                     timeline_id: TIMELINE_ID,
   12499           12 :                     kind: BranchPoint,
   12500           12 :                 },
   12501           12 :                 SegmentMeta {
   12502           12 :                     segment: Segment {
   12503           12 :                         parent: None,
   12504           12 :                         lsn: 0x40,
   12505           12 :                         size: None,
   12506           12 :                         needed: false,
   12507           12 :                     },
   12508           12 :                     timeline_id: TIMELINE_ID,
   12509           12 :                     kind: BranchPoint,
   12510           12 :                 },
   12511           12 :                 SegmentMeta {
   12512           12 :                     segment: Segment {
   12513           12 :                         parent: None,
   12514           12 :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12515           12 :                         size: None,
   12516           12 :                         needed: true,
   12517           12 :                     },
   12518           12 :                     timeline_id: TIMELINE_ID,
   12519           12 :                     kind: BranchEnd,
   12520           12 :                 },
   12521           12 :             ]
   12522           12 :         );
   12523           12 :         Ok(())
   12524           12 :     }
   12525              : }
        

Generated by: LCOV version 2.1-beta